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.

fix: require provisioned runtime before advertising previews

Juan Denis0894b8ff5bda
diff --git a/backend/app/models/application_preview.py b/backend/app/models/application_preview.py
index 53201d25..1f35fd58 100644
--- a/backend/app/models/application_preview.py
+++ b/backend/app/models/application_preview.py
@@ -27,6 +27,7 @@ class ApplicationPreview(TimestampMixin, JsonColumnMixin, db.Model):
STATUS_RUNNING = 'running'
STATUS_STOPPED = 'stopped'
STATUS_FAILED = 'failed'
+ STATUS_UNAVAILABLE = 'unavailable'
STATUS_DESTROYED = 'destroyed'
id = db.Column(db.Integer, primary_key=True)
@@ -60,16 +61,27 @@ class ApplicationPreview(TimestampMixin, JsonColumnMixin, db.Model):
self._json_write('container_ids', list(ids or []), falsy='[]')
def to_dict(self):
+ container_ids = self.get_container_ids()
+ # Older generic previews were marked running after config generation
+ # alone. Do not advertise those rows as a deployed runtime on reads.
+ status = self.status
+ if status == self.STATUS_RUNNING and not container_ids:
+ status = self.STATUS_UNAVAILABLE
return {
'id': self.id,
'application_id': self.application_id,
'pr_number': self.pr_number,
'pr_title': self.pr_title,
'branch': self.branch,
- 'status': self.status,
+ 'status': status,
+ 'status_reason': (
+ 'No provisioned runtime is recorded for this preview.'
+ if status == self.STATUS_UNAVAILABLE else None
+ ),
'domain': self.domain,
- 'url': (f'https://{self.domain}' if self.domain else None),
- 'container_ids': self.get_container_ids(),
+ 'url': (f'https://{self.domain}'
+ if self.domain and status == self.STATUS_RUNNING and container_ids else None),
+ 'container_ids': container_ids,
'commit_sha': self.commit_sha,
'short_sha': self.commit_sha[:7] if self.commit_sha else None,
'expires_at': self.expires_at.isoformat() if self.expires_at else None,
diff --git a/backend/app/services/preview_service.py b/backend/app/services/preview_service.py
index 90836b58..9c75d567 100644
--- a/backend/app/services/preview_service.py
+++ b/backend/app/services/preview_service.py
@@ -287,9 +287,12 @@ class PreviewService:
# Best-effort provisioning — degrade gracefully when unavailable.
provisioned = cls._provision(app, preview)
- preview.status = (ApplicationPreview.STATUS_RUNNING
- if provisioned.get('ok')
- else ApplicationPreview.STATUS_FAILED)
+ if provisioned.get('unsupported'):
+ preview.status = ApplicationPreview.STATUS_UNAVAILABLE
+ elif provisioned.get('ok') and provisioned.get('container_ids'):
+ preview.status = ApplicationPreview.STATUS_RUNNING
+ else:
+ preview.status = ApplicationPreview.STATUS_FAILED
if provisioned.get('container_ids'):
preview.set_container_ids(provisioned['container_ids'])
db.session.commit()
@@ -306,11 +309,9 @@ class PreviewService:
def _provision(cls, app, preview):
"""Best-effort real provisioning. Returns ``{'ok': bool, 'container_ids': [...]}``.
- For WordPress apps, delegate to the WP preview hook. For other app types
- we currently only record the row + domain (a deeper Docker clone is a
- roadmap item); we still report ``ok`` so the preview shows as running in
- environments where the row is all that's expected. All failures are
- swallowed and surfaced as ``ok: False``.
+ WordPress delegates to its preview hook. Generic config generation is
+ not provisioning: until a runtime provisioner exists, report unsupported.
+ A provider must explicitly report success and return runtime identifiers.
"""
try:
if getattr(app, 'app_type', None) == 'wordpress':
@@ -323,7 +324,7 @@ class PreviewService:
res = WordPressService.create_preview_instance(
site, preview.pr_number, domain=preview.domain,
branch=preview.branch)
- return {'ok': bool(res.get('success', True)),
+ return {'ok': bool(res.get('success', False)),
'container_ids': res.get('container_ids', [])}
except Exception as exc:
logger.info('WP preview provisioning unavailable: %s', exc)
@@ -338,7 +339,7 @@ class PreviewService:
manifest_preview = ManifestPreviewService.build_preview_config(app, preview)
except Exception as exc:
logger.info('manifest preview config unavailable: %s', exc)
- return {'ok': True, 'container_ids': [],
+ return {'ok': False, 'unsupported': True, 'container_ids': [],
'manifest_preview': manifest_preview}
except Exception as exc:
logger.info('preview provisioning unavailable: %s', exc)
diff --git a/backend/tests/test_previews.py b/backend/tests/test_previews.py
index 27cfdf3e..6da064d2 100644
--- a/backend/tests/test_previews.py
+++ b/backend/tests/test_previews.py
@@ -156,11 +156,12 @@ def test_create_and_destroy_writes_rows_and_flips_status(app):
'pr_title': 'Add X',
})
assert created.get('pr_number') == 12
- assert created.get('status') == ApplicationPreview.STATUS_RUNNING
+ assert created.get('status') == ApplicationPreview.STATUS_UNAVAILABLE
+ assert created['url'] is None
assert created.get('domain') # a domain was rendered
row = ApplicationPreview.query.filter_by(application_id=a.id, pr_number=12).first()
- assert row is not None and row.status == ApplicationPreview.STATUS_RUNNING
+ assert row is not None and row.status == ApplicationPreview.STATUS_UNAVAILABLE
destroyed = PreviewService.destroy_preview(row.id)
assert destroyed.get('status') == ApplicationPreview.STATUS_DESTROYED
@@ -217,3 +218,31 @@ def test_reconcile_against_db_rows(app):
open_prs=[{'pr_number': 7, 'commit_sha': 'new'}],
active_previews=[live])
assert [p['pr_number'] for p in plan['to_update']] == [7]
+
+
+def test_preview_requires_success_and_runtime_ids(app, monkeypatch):
+ with app.app_context():
+ a = _mk_app(name='runtime-proof')
+ PreviewService.enable_previews(a.id, {'enabled': True})
+ for number, result, expected in [
+ (1, {'ok': True, 'container_ids': ['runtime']}, 'running'),
+ (2, {'ok': True, 'container_ids': []}, 'failed'),
+ (3, {'ok': False, 'container_ids': ['runtime']}, 'failed'),
+ (4, {'container_ids': ['runtime']}, 'failed'),
+ ]:
+ monkeypatch.setattr(PreviewService, '_provision', lambda *a, **kw: result)
+ row = PreviewService.create_preview(a, {'pr_number': number})
+ assert row['status'] == expected
+ assert bool(row['url']) == (expected == 'running')
+
+
+def test_legacy_preview_without_runtime_is_not_advertised():
+ row = ApplicationPreview(status='running', domain='pr.example.test')
+ assert row.to_dict()['status'] == 'unavailable'
+ assert row.to_dict()['url'] is None
+ assert row.status == 'running' # reads do not mutate persistence
+ row.set_container_ids(['runtime'])
+ assert row.to_dict()['url'] == 'https://pr.example.test'
+ for status in ('failed', 'stopped', 'destroyed', 'building', 'queued'):
+ row.status = status
+ assert row.to_dict()['url'] is None
diff --git a/frontend/src/components/previews/PreviewList.jsx b/frontend/src/components/previews/PreviewList.jsx
index d56e8b29..0f1f649b 100644
--- a/frontend/src/components/previews/PreviewList.jsx
+++ b/frontend/src/components/previews/PreviewList.jsx
@@ -87,8 +87,12 @@ const PreviewList = ({ appId }) => {
async function handleRedeploy(preview) {
setBusyId(preview.id);
try {
- await api.redeployPreview(appId, preview.id);
- toast?.success?.(t('app.previewList.redeployingPreviewForPr', 'Redeploying preview for PR #{{prnumber}}', { prnumber: preview.pr_number }));
+ const result = await api.redeployPreview(appId, preview.id);
+ if (result.status === 'unavailable' || result.status === 'failed') {
+ toastError(toast, t('app.previewList.previewNotDeployed', 'The preview was not deployed. Review its status below.'));
+ } else {
+ toast?.success?.(t('app.previewList.redeployingPreviewForPr', 'Redeploying preview for PR #{{prnumber}}', { prnumber: preview.pr_number }));
+ }
await load();
} catch (err) {
toastError(toast, t('app.previewList.redeployFailed', "Couldn't redeploy the preview."), err);
@@ -133,7 +137,7 @@ const PreviewList = ({ appId }) => {
<div>
<h3>{t('app.previewList.prPreviewEnvironments', 'PR preview environments')}</h3>
<p className="preview-settings__hint">
- {t('app.previewList.deployAnIsolatedPreviewOfEach', 'Deploy an isolated preview of each open pull request to a temporary domain, and tear it down when the PR closes.')}
+ {t('app.previewList.supportedProvisioners', 'Preview deployment requires a supported runtime provisioner. Generic application previews are not available yet. A domain alone does not mean a preview is deployed.')}
</p>
</div>
</div>
@@ -207,7 +211,7 @@ const PreviewList = ({ appId }) => {
<div className="preview-item__meta">
{p.branch && <span className="preview-item__branch mono">{p.branch}</span>}
{p.short_sha && <span className="preview-item__sha mono">{p.short_sha}</span>}
- {p.url && (
+ {p.url && p.status === 'running' && (
<a
className="preview-item__url"
href={p.url}
@@ -218,9 +222,14 @@ const PreviewList = ({ appId }) => {
</a>
)}
</div>
+ {p.status === 'unavailable' && (
+ <p className="preview-settings__hint">
+ {t('app.previewList.noRuntime', 'No provisioned runtime is recorded for this preview. Its URL is unavailable.')}
+ </p>
+ )}
</div>
<div className="preview-item__actions">
- {p.url && (
+ {p.url && p.status === 'running' && (
<Button variant="ghost" size="sm" asChild>
<a href={p.url} target="_blank" rel="noopener noreferrer">
<ExternalLink size={15} />