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.

feat(wordpress): run environment promotions as watchable deployments

Juan Denis3c84d152ea01
diff --git a/ROADMAP.md b/ROADMAP.md
index 5f035ea4..9242998b 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -603,6 +603,7 @@ happen live, and debug failures entirely from the UI.
- [x] Streaming build output with a step timeline, per-step durations, and live elapsed time
- [x] Failure cards showing the real error tail with plain-language hints and one-click retry
- [x] Unified batched run-log layer (database persistence + WebSocket push, polling fallback)
+- [x] Extensions can put their own long-running work on the same console — WordPress environment promotions are the first, with live steps, logs and retry
## Extension Platform
diff --git a/backend/app/plugins_sdk/deploys_sdk.py b/backend/app/plugins_sdk/deploys_sdk.py
index 48d7612c..59b65afa 100644
--- a/backend/app/plugins_sdk/deploys_sdk.py
+++ b/backend/app/plugins_sdk/deploys_sdk.py
@@ -26,10 +26,9 @@ retryable background work that nobody watches.
from contextlib import contextmanager
-from app import db
from app.services import deploy_kind_registry
from app.services.deployment_job_service import DeploymentJobService
-from app.services.run_log_service import RunLogStream
+from app.services.run_log_service import stream_for
class DeploysSdk:
@@ -49,7 +48,9 @@ class DeploysSdk:
``steps`` are the names the console shows, in order; the returned
``job_id`` addresses ``/deployments/<id>`` immediately, so a caller can
- redirect there before the work begins.
+ redirect there before the work begins. Everything else the handler will
+ need goes in ``plan`` — including ``title``, which is what the console
+ heads the run with instead of falling back to the bare kind.
"""
return DeploymentJobService.start_registered(
kind, steps=steps, app_id=app_id, server_id=server_id,
@@ -64,10 +65,24 @@ class DeploysSdk:
def log(self, job, message, level='info', step_index=None):
"""Append one line to a job's console."""
- stream = RunLogStream.for_job(job)
+ stream = stream_for(job)
stream.log(level, message, step_index=step_index)
stream.flush()
+ def progress(self, job, index, name=None):
+ """Move *job* onto step *index*, logging *name* as the console line.
+
+ For work whose progress arrives through a callback the handler doesn't
+ control — an existing service that already reports ``(step, message)``.
+ When the handler owns the sequence itself, ``steps()`` reads better and
+ records the failing step for you.
+ """
+ stream = stream_for(job)
+ stream.set_step(index, name)
+ if name:
+ stream.log('info', name, step_index=index)
+ stream.flush()
+
@contextmanager
def steps(self, job):
"""Walk a job's steps, keeping progress and logs in step.
@@ -79,16 +94,16 @@ class DeploysSdk:
without that, a failure shows only a stack trace and no indication of
how far the deployment got.
"""
- stream = RunLogStream.for_job(job)
+ stream = stream_for(job)
state = {'index': 0}
@contextmanager
def step(name):
state['index'] += 1
index = state['index']
- job.current_step = index
- job.current_step_name = name
- db.session.commit()
+ # set_step (rather than a hand-rolled row update) is what records
+ # the per-step seconds the console shows and pushes the live status.
+ stream.set_step(index, name)
stream.log('info', f'→ {name}', step_index=index)
stream.flush()
try:
diff --git a/backend/app/services/deployment_job_service.py b/backend/app/services/deployment_job_service.py
index b991efae..0ae937e2 100644
--- a/backend/app/services/deployment_job_service.py
+++ b/backend/app/services/deployment_job_service.py
@@ -10,7 +10,7 @@ from app import db
from app.models import Application, Server
from app.models.deployment_job import DeploymentJob
from app.services.deployment_runner import DeploymentPlanRunner
-from app.services.run_log_service import append_log, RunLogStream
+from app.services.run_log_service import append_log, stream_for
from app.services.docker_service import DockerService
from app.services.template_service import TemplateService
from app.services.telemetry_service import generate_correlation_id
@@ -607,18 +607,21 @@ class DeploymentJobService:
job.started_at = job.started_at or datetime.utcnow()
db.session.commit()
- stream = RunLogStream.for_job(job)
+ # The same stream the handler logs through (see run_log_service.
+ # stream_for), so closing it here persists the step timings the handler
+ # recorded rather than an empty second buffer's.
+ stream = stream_for(job)
try:
result = handler(job) or {}
except Exception as exc:
logger.exception('Deployment kind %s raised', job.kind)
stream.log('error', f'{job.kind} failed: {exc}')
- stream.flush()
db.session.rollback()
job.status = 'failed'
job.error_message = str(exc)
job.completed_at = datetime.utcnow()
db.session.commit()
+ stream.close('failed', error_message=str(exc))
return {'success': False, 'error': str(exc), 'job_id': job.id}
stream.flush()
@@ -629,6 +632,13 @@ class DeploymentJobService:
job.error_message = result.get('error') or f'{job.kind} failed'
job.completed_at = datetime.utcnow()
db.session.commit()
+ if job.status == 'failed' and job.error_message:
+ # A handler that reported failure by return value logged nothing;
+ # without this the console shows a failed run with no reason in it.
+ stream.log('error', job.error_message)
+ # close() persists step timings (and, on failure, the tail + hint) into
+ # the job's result and emits the terminal status the console listens for.
+ stream.close(job.status, error_message=job.error_message)
# Handler extras first: the job's own status is the authoritative
# outcome and must not be overwritten by a handler that finalised the
# job one way and then returned the other.
diff --git a/backend/app/services/run_log_service.py b/backend/app/services/run_log_service.py
index 6fc2d115..640ee26c 100644
--- a/backend/app/services/run_log_service.py
+++ b/backend/app/services/run_log_service.py
@@ -367,6 +367,29 @@ def _trim_data(data: Any) -> Any:
return data
+_STREAM_ATTR = '_run_log_stream'
+
+
+def stream_for(job: DeploymentJob) -> RunLogStream:
+ """Return the one stream for *job*, creating it on first use.
+
+ Used where the logging and the terminal ``close()`` sit in different places:
+ a plugin handler logs through ``plugins_sdk.deploys`` while the runner
+ around it owns the close. Two independent streams would mean two buffers,
+ and the step timings recorded by the handler's would be dropped by the
+ runner's close. The instance is cached on the job object, so the sharing
+ scope is exactly the session that is running it.
+ """
+ stream = getattr(job, _STREAM_ATTR, None)
+ if stream is None:
+ stream = RunLogStream.for_job(job)
+ try:
+ setattr(job, _STREAM_ATTR, stream)
+ except Exception:
+ pass
+ return stream
+
+
def append_log(job: DeploymentJob, level: str, message: str, data: Any = None,
step_index: Optional[int] = None) -> None:
"""Immediate, persisted single log line for fire-and-forget annotations
diff --git a/backend/tests/test_wp_promote_deploy_job.py b/backend/tests/test_wp_promote_deploy_job.py
new file mode 100644
index 00000000..8a95abcb
--- /dev/null
+++ b/backend/tests/test_wp_promote_deploy_job.py
@@ -0,0 +1,260 @@
+"""WordPress promotion runs as a deployment (kind ``wordpress.promote``).
+
+Promotion used to run in the request thread: no console, no log stream, no
+retry, and a page that could only show a progress bar it had to keep alive
+itself. It is now a registered deployment kind, so it gets all of that from the
+platform — while the PromotionJob rows stay exactly where they were, because
+they carry ``pre_promotion_snapshot_id``, the pointer a rollback needs.
+"""
+
+import pytest
+
+from app import db
+from app.models.application import Application
+from app.models.deployment_job import DeploymentJob, DeploymentJobLog
+from app.models.promotion_job import PromotionJob
+from app.models.wordpress_site import WordPressSite
+from app.services import deploy_kind_registry, wordpress_bridge
+from app.services.deployment_job_service import DeploymentJobService
+from app.services.environment_pipeline_service import EnvironmentPipelineService
+
+
+def pipeline_module():
+ """The extension blueprint module, re-contributing its deployment kind.
+
+ The registry is a process-wide singleton that other suites clear, and the
+ module only registers on first import — so re-register explicitly rather
+ than depending on which test file ran first.
+ """
+ module = wordpress_bridge.load('environment_pipeline')
+ module.register_deploy_kinds()
+ return module
+
+
+def sites(app, auth_headers):
+ """A production site and a staging environment beneath it."""
+ from app.models import User
+
+ with app.app_context():
+ admin = User.query.filter_by(username='testadmin').first()
+
+ def _site(name, env_type, production_site_id=None):
+ application = Application(name=name, app_type='docker', status='running',
+ root_path=f'/srv/{name}', user_id=admin.id)
+ db.session.add(application)
+ db.session.commit()
+ site = WordPressSite(
+ application_id=application.id, db_name=f'{name}_db', db_user='wp',
+ db_host='localhost', environment_type=env_type,
+ is_production=(env_type == 'production'),
+ production_site_id=production_site_id,
+ )
+ db.session.add(site)
+ db.session.commit()
+ return site.id
+
+ prod_id = _site('wp-prod', 'production')
+ staging_id = _site('wp-staging', 'staging', production_site_id=prod_id)
+ return {'prod': prod_id, 'staging': staging_id}
+
+
+def _promote(client, auth_headers, sites, promotion_type='code', config=None):
+ return client.post(
+ f'/api/v1/wordpress/pipelines/{sites["prod"]}/promote',
+ json={
+ 'source_env_id': sites['staging'],
+ 'target_env_id': sites['prod'],
+ 'type': promotion_type,
+ 'config': config or {},
+ },
+ headers=auth_headers,
+ )
+
+
+class TestEndpoint:
+ def test_promote_queues_a_deployment_and_returns_its_id(
+ self, app, client, auth_headers, sites, pipeline_module, monkeypatch):
+ calls = []
+ monkeypatch.setattr(EnvironmentPipelineService, 'promote_code',
+ classmethod(lambda cls, *a, **kw: calls.append(kw) or {'success': True}))
+
+ res = _promote(client, auth_headers, sites)
+
+ assert res.status_code == 202
+ body = res.get_json()
+ assert body['queued'] is True
+ job_id = body['job_id']
+
+ with app.app_context():
+ job = DeploymentJob.query.get(job_id)
+ assert job.kind == 'wordpress.promote'
+ assert job.status == 'pending'
+ plan = job.get_plan()
+ assert plan['source_env_id'] == sites['staging']
+ assert plan['target_env_id'] == sites['prod']
+ assert plan['promotion_type'] == 'code'
+ # The console reads its heading from the plan, so an unknown kind
+ # still gets a sentence instead of "Deployment · wordpress.promote".
+ assert plan['title'] == 'Promoting code from staging to production'
+ assert [s['name'] for s in plan['steps']] == pipeline_module.PROMOTION_STEPS['code']
+
+ # The point of the change: the request no longer does the promoting.
+ assert calls == []
+
+ def test_full_promotion_plans_both_halves(
+ self, app, client, auth_headers, sites, pipeline_module):
+ res = _promote(client, auth_headers, sites, promotion_type='full')
+ assert res.status_code == 202
+
+ with app.app_context():
+ job = DeploymentJob.query.get(res.get_json()['job_id'])
+ names = [s['name'] for s in job.get_plan()['steps']]
+ assert len(names) == 10
+ assert names[0].startswith('Code · ')
+ assert names[5].startswith('Database · ')
+
+ def test_unknown_promotion_type_is_still_rejected(
+ self, client, auth_headers, sites, pipeline_module):
+ res = _promote(client, auth_headers, sites, promotion_type='everything')
+ assert res.status_code == 400
+
+ def test_a_locked_environment_is_refused_before_anything_is_queued(
+ self, app, client, auth_headers, sites, pipeline_module):
+ # Queueing first would send the user to a console that fails a second
+ # later; the answer is knowable now.
+ with app.app_context():
+ site = WordPressSite.query.get(sites['prod'])
+ site.is_locked = True
+ site.locked_reason = 'Sync in progress'
+ db.session.commit()
+
+ res = _promote(client, auth_headers, sites)
+
+ assert res.status_code == 400
+ assert 'locked' in res.get_json()['error']
+ with app.app_context():
+ assert DeploymentJob.query.filter_by(kind='wordpress.promote').count() == 0
+
+
+class TestHandler:
+ def _run(self, client, auth_headers, sites, promotion_type='code'):
+ res = _promote(client, auth_headers, sites, promotion_type=promotion_type)
+ assert res.status_code == 202
+ job_id = res.get_json()['job_id']
+ return job_id, DeploymentJobService.run_job(job_id)
+
+ def test_promotion_succeeds_and_walks_the_console_steps(
+ self, app, client, auth_headers, sites, pipeline_module, monkeypatch):
+ def fake_promote(cls, source_id, target_id, config=None, user_id=None,
+ progress_callback=None):
+ for step, message in enumerate(
+ ['Locking environments...', 'Creating pre-promotion snapshot...',
+ 'Syncing code files...', 'Flushing caches...', 'Complete'], start=1):
+ EnvironmentPipelineService._emit_progress(progress_callback, step, 5, message)
+ return {'success': True, 'message': 'Code promoted from staging to production'}
+
+ monkeypatch.setattr(EnvironmentPipelineService, 'promote_code',
+ classmethod(fake_promote))
+
+ job_id, result = self._run(client, auth_headers, sites)
+ assert result['success'] is True
+
+ with app.app_context():
+ job = DeploymentJob.query.get(job_id)
+ assert job.status == 'succeeded'
+ assert job.current_step == 5
+ # Timings are what the console's step strip renders its durations
+ # from; they only survive because the handler and the runner share
+ # one log stream.
+ assert len(job.get_result()['step_timings']) == 5
+ messages = [row.message for row in
+ DeploymentJobLog.query.filter_by(job_id=job_id).all()]
+ assert 'Syncing code files...' in messages
+
+ def test_full_promotion_progress_never_goes_backwards(
+ self, app, client, auth_headers, sites, pipeline_module, monkeypatch):
+ # promote_full runs two five-step halves and restarts its own numbering
+ # at 1 for the second — the console must not rewind to step 1 halfway.
+ def fake_full(cls, source_id, target_id, config=None, user_id=None,
+ progress_callback=None):
+ for _half in range(2):
+ for step in range(1, 6):
+ EnvironmentPipelineService._emit_progress(
+ progress_callback, step, 5, f'Step {step}')
+ return {'success': True, 'message': 'Full promotion completed'}
+
+ monkeypatch.setattr(EnvironmentPipelineService, 'promote_full',
+ classmethod(fake_full))
+
+ job_id, result = self._run(client, auth_headers, sites, promotion_type='full')
+ assert result['success'] is True
+
+ with app.app_context():
+ job = DeploymentJob.query.get(job_id)
+ assert job.current_step == 10
+ assert job.status == 'succeeded'
+
+ def test_failed_promotion_fails_the_job_with_the_reason_in_the_console(
+ self, app, client, auth_headers, sites, pipeline_module, monkeypatch):
+ monkeypatch.setattr(
+ EnvironmentPipelineService, 'promote_code',
+ classmethod(lambda cls, *a, **kw: {'success': False, 'error': 'rsync refused'}))
+
+ job_id, result = self._run(client, auth_headers, sites)
+ assert result['success'] is False
+
+ with app.app_context():
+ job = DeploymentJob.query.get(job_id)
+ assert job.status == 'failed'
+ assert job.error_message == 'rsync refused'
+ messages = [row.message for row in
+ DeploymentJobLog.query.filter_by(job_id=job_id).all()]
+ assert 'rsync refused' in messages
+
+ def test_promotion_rows_are_linked_even_when_the_promotion_fails(
+ self, app, client, auth_headers, sites, pipeline_module, monkeypatch):
+ # The rollback pointer lives on PromotionJob, and a failed promotion is
+ # precisely when someone needs it — so the link can't come from the
+ # service's success-only return value.
+ def fake_promote(cls, source_id, target_id, config=None, user_id=None,
+ progress_callback=None):
+ row = PromotionJob(source_site_id=source_id, target_site_id=target_id,
+ promotion_type='code', status='failed')
+ db.session.add(row)
+ db.session.commit()
+ return {'success': False, 'error': 'died halfway'}
+
+ monkeypatch.setattr(EnvironmentPipelineService, 'promote_code',
+ classmethod(fake_promote))
+
+ job_id, _ = self._run(client, auth_headers, sites)
+
+ with app.app_context():
+ job = DeploymentJob.query.get(job_id)
+ linked = job.get_result()['promotion_job_ids']
+ assert len(linked) == 1
+ assert PromotionJob.query.get(linked[0]).status == 'failed'
+
+ def test_a_raising_promotion_still_ends_the_job(
+ self, app, client, auth_headers, sites, pipeline_module, monkeypatch):
+ def explode(cls, *args, **kwargs):
+ raise RuntimeError('docker went away')
+
+ monkeypatch.setattr(EnvironmentPipelineService, 'promote_code',
+ classmethod(explode))
+
+ job_id, result = self._run(client, auth_headers, sites)
+ assert result['success'] is False
+
+ with app.app_context():
+ job = DeploymentJob.query.get(job_id)
+ assert job.status == 'failed'
+ assert 'docker went away' in job.error_message
+
+
+def test_promotion_kind_is_contributed_by_the_extension(pipeline_module):
+ assert deploy_kind_registry.get('wordpress.promote') is pipeline_module.run_promotion
+ # Namespaced, so it can never shadow a core deployment kind.
+ assert 'wordpress.promote' in deploy_kind_registry.kinds()
diff --git a/builtin-extensions/serverkit-wordpress/backend/environment_pipeline.py b/builtin-extensions/serverkit-wordpress/backend/environment_pipeline.py
index cef6d011..d3dc7bbf 100644
--- a/builtin-extensions/serverkit-wordpress/backend/environment_pipeline.py
+++ b/builtin-extensions/serverkit-wordpress/backend/environment_pipeline.py
@@ -17,6 +17,7 @@ from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db, limiter
+from app.plugins_sdk import deploys
from app.models.application import Application
from app.models.wordpress_site import WordPressSite
from app.models.environment_activity import EnvironmentActivity
@@ -312,12 +313,139 @@ def restart_environment(prod_id, env_id):
# =============================================================================
# Promotion
# =============================================================================
+#
+# A promotion is deployment-shaped work: it takes minutes, changes what is
+# running, can fail halfway, and someone wants to watch it. So it runs as a
+# registered deployment kind (plugins_sdk.deploys) rather than in the request
+# thread — which gets it the Deploy Console, live logs, retry and a row in
+# Deploy Activity, and returns a job id the UI can open immediately.
+#
+# The PromotionJob rows the pipeline service writes are NOT replaced by this:
+# they carry pre_promotion_snapshot_id, the rollback pointer, which is WordPress
+# domain that a generic DeploymentJob has no business holding. The deployment
+# records which promotions it produced instead (see _promotions_since).
+
+PROMOTION_KIND = 'wordpress.promote'
+
+# Mirrors what EnvironmentPipelineService emits through progress_callback, so
+# the console's pipeline strip and its log lines agree step for step.
+_CODE_STEPS = ['Locking environments', 'Creating pre-promotion snapshot',
+ 'Syncing code files', 'Flushing caches', 'Complete']
+_DATABASE_STEPS = ['Locking environments', 'Creating pre-promotion snapshot',
+ 'Cloning database with transformations', 'Flushing caches', 'Complete']
+PROMOTION_STEPS = {
+ 'code': _CODE_STEPS,
+ 'database': _DATABASE_STEPS,
+ # promote_full runs both halves back to back.
+ 'full': [f'Code · {name}' for name in _CODE_STEPS]
+ + [f'Database · {name}' for name in _DATABASE_STEPS],
+}
+
+
+def _promotion_progress(job, prod_id):
+ """Bridge the pipeline service's progress into the console and the pipeline page.
+
+ The service reports ``(step, total, message)``. A full promotion runs two
+ five-step halves and restarts its numbering at 1 for the second, so copying
+ the raw step number would send the console's strip backwards; carrying an
+ offset across the reset keeps it moving forward. The original payload still
+ goes out over the WebSocket, so the pipeline page's own progress bar behaves
+ exactly as it did when this ran in the request thread.
+ """
+ state = {'last': 0, 'offset': 0}
+
+ def emit(data):
+ step = int(data.get('step') or 0)
+ if step <= state['last']:
+ state['offset'] += state['last']
+ state['last'] = step
+ deploys.progress(job, state['offset'] + step, data.get('message'))
+ _emit_pipeline_event(prod_id, 'operation_progress', data)
+
+ return emit
+
+
+def _promotions_since(watermark, source_id, target_id):
+ """PromotionJob ids this run created, newest work last.
+
+ Read by id watermark rather than from the service's return value because
+ promote_* only reports the job on success — and a failed promotion is
+ exactly when someone needs the row, since it holds the snapshot to roll
+ back to.
+ """
+ rows = PromotionJob.query.filter(
+ PromotionJob.id > watermark,
+ PromotionJob.source_site_id == source_id,
+ PromotionJob.target_site_id == target_id,
+ ).order_by(PromotionJob.id).all()
+ return [row.id for row in rows]
+
+
+def run_promotion(job):
+ """Deployment handler for ``wordpress.promote``."""
+ plan = job.get_plan() or {}
+ prod_id = plan.get('prod_id')
+ source_id = plan.get('source_env_id')
+ target_id = plan.get('target_env_id')
+ promotion_type = plan.get('promotion_type') or 'code'
+
+ promote_fn = {
+ 'code': EnvironmentPipelineService.promote_code,
+ 'database': EnvironmentPipelineService.promote_database,
+ 'full': EnvironmentPipelineService.promote_full,
+ }.get(promotion_type)
+ if promote_fn is None:
+ # The endpoint validates the type, but a retry replays a stored plan.
+ return {'success': False, 'error': f'Unknown promotion type: {promotion_type}'}
+
+ watermark = db.session.query(db.func.max(PromotionJob.id)).scalar() or 0
+ result = promote_fn(
+ source_id, target_id,
+ config=plan.get('config') or {},
+ user_id=plan.get('user_id'),
+ progress_callback=_promotion_progress(job, prod_id),
+ ) or {}
+
+ promotion_ids = _promotions_since(watermark, source_id, target_id)
+ if promotion_ids:
+ job.set_result({**(job.get_result() or {}), 'promotion_job_ids': promotion_ids})
+ db.session.commit()
+
+ succeeded = bool(result.get('success'))
+ _emit_pipeline_event(prod_id, 'promotion_completed' if succeeded else 'promotion_failed', {
+ 'source_env_id': source_id,
+ 'target_env_id': target_id,
+ 'type': promotion_type,
+ 'success': succeeded,
+ 'message': result.get('message') or result.get('error'),
+ 'job_id': job.id,
+ })
+
+ if not succeeded:
+ return {'success': False, 'error': result.get('error') or 'Promotion failed'}
+
+ deploys.log(job, result.get('message') or 'Promotion complete')
+ return {'success': True, 'message': result.get('message'),
+ 'promotion_job_ids': promotion_ids}
+
+
+def register_deploy_kinds():
+ """Contribute the promotion kind. Idempotent — safe to call per app setup."""
+ deploys.register(PROMOTION_KIND, run_promotion, replace=True)
+
+
+register_deploy_kinds()
+
@environment_pipeline_bp.route('/<int:prod_id>/promote', methods=['POST'])
@jwt_required()
@limiter.limit("5 per minute")
def promote(prod_id):
- """Promote code/DB between environments.
+ """Queue a code/DB promotion between environments.
+
+ Returns 202 with the deployment ``job_id`` — the work runs as a
+ ``wordpress.promote`` deployment (see run_promotion above), so the caller
+ can open /deployments/<job_id> for logs, steps and retry.
Body: {
source_env_id: int,
@@ -367,51 +495,63 @@ def promote(prod_id):
if env_site.id != prod_id and env_site.production_site_id != prod_id:
return jsonify({'error': f'{label} environment does not belong to this project'}), 400
+ # The pipeline service checks the locks again when it runs (they can be
+ # taken in between), but a lock we can already see should be answered here
+ # rather than by sending the user to a console that fails a second later.
+ for env_site, label in [(source_site, 'Source'), (target_site, 'Target')]:
+ if env_site.is_locked:
+ return jsonify({'error': f'{label} environment is locked: {env_site.locked_reason}'}), 400
+
config = data.get('config', {})
+ source_label = source_site.environment_type or 'source'
+ target_label = target_site.environment_type or 'target'
+
# Emit WebSocket event for operation start
_emit_pipeline_event(prod_id, 'promotion_started', {
'source_env_id': source_env_id,
'target_env_id': target_env_id,
'type': promotion_type,
- 'message': f'Promoting {promotion_type} from {source_site.environment_type} to {target_site.environment_type}...'
+ 'message': f'Promoting {promotion_type} from {source_label} to {target_label}...'
})
- # Progress callback emits WebSocket events
- def progress_callback(progress_data):
- _emit_pipeline_event(prod_id, 'operation_progress', progress_data)
-
- # Run promotion (long-running operations run in the request thread)
- if promotion_type == 'code':
- result = EnvironmentPipelineService.promote_code(
- source_env_id, target_env_id, config=config, user_id=user_id,
- progress_callback=progress_callback
- )
- elif promotion_type == 'database':
- result = EnvironmentPipelineService.promote_database(
- source_env_id, target_env_id, config=config, user_id=user_id,
- progress_callback=progress_callback
- )
- else:
- result = EnvironmentPipelineService.promote_full(
- source_env_id, target_env_id, config=config, user_id=user_id,
- progress_callback=progress_callback
- )
-
- # Emit completion event
- _emit_pipeline_event(prod_id, 'promotion_completed' if result.get('success') else 'promotion_failed', {
- 'source_env_id': source_env_id,
- 'target_env_id': target_env_id,
- 'type': promotion_type,
- 'success': result.get('success', False),
- 'message': result.get('message') or result.get('error'),
- })
+ result = deploys.start(
+ PROMOTION_KIND,
+ steps=PROMOTION_STEPS[promotion_type],
+ app_id=target_site.application_id,
+ user_id=user_id,
+ plan={
+ 'title': f'Promoting {promotion_type} from {source_label} to {target_label}',
+ 'prod_id': prod_id,
+ 'source_env_id': source_env_id,
+ 'target_env_id': target_env_id,
+ 'promotion_type': promotion_type,
+ 'config': config,
+ 'user_id': user_id,
+ },
+ )
- if result.get('success'):
- return jsonify(result)
- else:
+ if not result.get('success'):
+ # Queueing failed, so nothing will run — say so on the same channel a
+ # failed promotion uses, or the page waits on an operation forever.
+ _emit_pipeline_event(prod_id, 'promotion_failed', {
+ 'source_env_id': source_env_id,
+ 'target_env_id': target_env_id,
+ 'type': promotion_type,
+ 'success': False,
+ 'message': result.get('error'),
+ })
return jsonify(result), 500
+ # 202: the promotion is queued, not done. Progress arrives on the pipeline
+ # socket as before, and job_id opens the full console at /deployments/<id>.
+ return jsonify({
+ 'success': True,
+ 'queued': True,
+ 'job_id': result['job_id'],
+ 'message': f'Promotion queued: {promotion_type} from {source_label} to {target_label}',
+ }), 202
+
# =============================================================================
# Sync from Production
diff --git a/frontend/src/pages/DeployConsole.jsx b/frontend/src/pages/DeployConsole.jsx
index 5d8079bc..bcdf6536 100644
--- a/frontend/src/pages/DeployConsole.jsx
+++ b/frontend/src/pages/DeployConsole.jsx
@@ -37,6 +37,9 @@ const fmtElapsed = (ms) => {
function humanizeTitle(job) {
if (!job) return 'Deployment';
+ // Kinds contributed by plugins name their own run in the plan, so the
+ // console reads properly without a branch per kind here.
+ if (job.plan?.title) return job.plan.title;
if (job.kind === 'demo_deploy') {
const scenario = job.plan?.scenario || job.result?.scenario;
return `Test deployment${scenario ? ` — ${scenario}` : ''}`;
diff --git a/frontend/src/pages/WordPressProject.jsx b/frontend/src/pages/WordPressProject.jsx
index 65c649df..8d1c8332 100644
--- a/frontend/src/pages/WordPressProject.jsx
+++ b/frontend/src/pages/WordPressProject.jsx
@@ -158,14 +158,17 @@ const WordPressProject = () => {
}, []);
const handleDoPromote = useCallback(async (config) => {
- toast.info('Starting promotion...', { duration: 3000 });
try {
- await wordpressApi.promoteEnvironment(id, config);
+ const res = await wordpressApi.promoteEnvironment(id, config);
setPromoteModal(null);
+ // A promotion is a deployment now: open its console, where the
+ // steps, live log and retry live.
+ if (res?.job_id) navigate(`/deployments/${res.job_id}`);
+ else toast.info('Promotion queued');
} catch (err) {
toast.error(err.message || 'Promotion failed');
}
- }, [id, toast]);
+ }, [id, navigate, toast]);
const handleSync = useCallback((env) => {
setSyncModal({ environment: env });