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(extensions): boot-time hook registration seam

Juan Denis57d82c8c8373
diff --git a/backend/app/services/extension_lifecycle.py b/backend/app/services/extension_lifecycle.py
index d59e4257..1d64dbd1 100644
--- a/backend/app/services/extension_lifecycle.py
+++ b/backend/app/services/extension_lifecycle.py
@@ -165,3 +165,37 @@ def remove_jobs(plugin, manifest):
db.session.commit()
except Exception as e:
logger.warning(f'Could not remove schedules for {plugin.slug}: {e}')
+
+
+# --------------------------------------------------------------------------- #
+# Core hooks (plan 52 D4 — hook inversion)
+# --------------------------------------------------------------------------- #
+
+def register_capabilities(plugin, manifest):
+ """Invoke the extension's core-hook registration function.
+
+ Manifest surface::
+
+ "core_hooks": "core_hooks:register" # zero-arg function under
+ # app.plugins.<slug>
+
+ The function registers the extension's entries into core-owned
+ registration seams (backup target kinds, event-catalog types, template
+ providers, …) so core keeps each engine while the extension supplies the
+ entry — an absent extension means the feature is absent, gracefully.
+
+ Called at install AND on every boot for active plugins (right beside
+ register_models/register_jobs), so the function MUST be idempotent.
+ Because it runs per boot rather than per module import, a seam registry
+ cleared since the last boot is refilled. Best-effort: a failure logs and
+ never blocks the load.
+ """
+ target = (manifest or {}).get('core_hooks')
+ if not target:
+ return
+ try:
+ fn = _import_target(plugin.slug, target)
+ if callable(fn):
+ fn()
+ except Exception as e:
+ logger.warning(f'Core-hook registration failed for {plugin.slug}: {e}')
diff --git a/backend/app/services/plugin_service.py b/backend/app/services/plugin_service.py
index 783c89a6..330a5a40 100644
--- a/backend/app/services/plugin_service.py
+++ b/backend/app/services/plugin_service.py
@@ -1010,6 +1010,7 @@ def _install_from_buffer(buf, source_url, source_type, user_id=None, force=False
from app.services import extension_lifecycle
extension_lifecycle.register_models(plugin, manifest)
extension_lifecycle.register_jobs(plugin, manifest)
+ extension_lifecycle.register_capabilities(plugin, manifest)
except Exception as e:
logger.warning(f'Extension lifecycle setup failed for {slug}: {e}')
try:
@@ -1350,13 +1351,14 @@ def load_all_plugins(app):
manifest = plugin.manifest or {}
_register_extra_blueprints(app.register_blueprint, plugin, manifest)
- # Re-establish the plugin's data models, jobs, and socket
- # namespace on boot (install-time registration doesn't survive
- # a restart).
+ # Re-establish the plugin's data models, jobs, core-hook
+ # registrations, and socket namespace on boot (install-time
+ # registration doesn't survive a restart).
try:
from app.services import extension_lifecycle
extension_lifecycle.register_models(plugin, manifest)
extension_lifecycle.register_jobs(plugin, manifest)
+ extension_lifecycle.register_capabilities(plugin, manifest)
from app.plugins_sdk import sockets as _ext_sockets
_ext_sockets.register_from_manifest(plugin, manifest)
except Exception as e:
@@ -1923,11 +1925,13 @@ def _seed_flagship_row(entry):
db.session.add(plugin)
db.session.commit()
- # Register plugin-owned data models / jobs / sockets, same as a copy-install.
+ # Register plugin-owned data models / jobs / core hooks / sockets, same as
+ # a copy-install.
try:
from app.services import extension_lifecycle
extension_lifecycle.register_models(plugin, manifest)
extension_lifecycle.register_jobs(plugin, manifest)
+ extension_lifecycle.register_capabilities(plugin, manifest)
from app.plugins_sdk import sockets as _ext_sockets
_ext_sockets.register_from_manifest(plugin, manifest)
except Exception as e:
diff --git a/builtin-extensions/serverkit-wordpress/backend/core_hooks.py b/builtin-extensions/serverkit-wordpress/backend/core_hooks.py
new file mode 100644
index 00000000..e1981b1e
--- /dev/null
+++ b/builtin-extensions/serverkit-wordpress/backend/core_hooks.py
@@ -0,0 +1,181 @@
+"""Core-hook registrations for the WordPress extension (plan 52, D4).
+
+Core keeps the engines — backup policies/runs/restore, the event bus catalog,
+the template catalog/installer — and this extension supplies its entries at
+load time through the manifest ``core_hooks`` seam
+(``extension_lifecycle.register_capabilities`` calls :func:`register` at
+install and on every boot while the extension is active).
+
+Everything here is idempotent: ``register`` runs once per boot (and once per
+install), and possibly again after a test cleared a registry.
+
+Absent extension = feature absent, gracefully:
+- no ``wordpress_site`` backup target type (policies that reference it report
+ "provider missing" instead of crashing),
+- no ``wordpress.*`` types in the event catalog,
+- no WordPress cards in the Templates grid, and template installs of the WP
+ templates refuse with a clear provider-missing error.
+"""
+import logging
+import os
+
+logger = logging.getLogger(__name__)
+
+SLUG = 'serverkit-wordpress'
+
+# The wordpress.* lifecycle events this extension emits (emitted via
+# EventService.emit_wp from the git-deploy / create / safe-update flows).
+# Catalog registration only — emission never validates against the catalog.
+WP_EVENT_TYPES = [
+ {'type': 'wordpress.site_down', 'category': 'WordPress', 'description': 'A WordPress site failed its health check'},
+ {'type': 'wordpress.site_up', 'category': 'WordPress', 'description': 'A WordPress site recovered after a failed health check'},
+ {'type': 'wordpress.created', 'category': 'WordPress', 'description': 'A WordPress site was created'},
+ {'type': 'wordpress.deleted', 'category': 'WordPress', 'description': 'A WordPress site was deleted'},
+ {'type': 'wordpress.backup_completed', 'category': 'WordPress', 'description': 'A WordPress site backup/snapshot completed'},
+ {'type': 'wordpress.updated', 'category': 'WordPress', 'description': 'A WordPress safe-update completed'},
+ {'type': 'wordpress.update_rolled_back', 'category': 'WordPress', 'description': 'A WordPress update was auto-rolled-back'},
+ {'type': 'wordpress.deployed', 'category': 'WordPress', 'description': 'A WordPress git deploy completed'},
+ {'type': 'wordpress.deploy_failed', 'category': 'WordPress', 'description': 'A WordPress git deploy failed'},
+]
+
+
+def register():
+ """Register every WordPress entry into the core seams. Idempotent."""
+ _register_backup_kind()
+ _register_event_types()
+ _register_template_provider()
+
+
+# --------------------------------------------------------------------------- #
+# Backup target kind: 'wordpress_site'
+# --------------------------------------------------------------------------- #
+
+def _register_backup_kind():
+ from app.services import backup_kind_registry
+ if backup_kind_registry.get('wordpress_site'):
+ return
+ backup_kind_registry.register(
+ 'wordpress_site',
+ resolve=_backup_resolve,
+ execute=_backup_execute,
+ restore=_backup_restore,
+ label='WordPress site',
+ restore_scopes=['full', 'files', 'database', 'tables'],
+ )
+
+
+def _backup_resolve(policy):
+ """Describe the live WordPress site behind a backup policy."""
+ from app.models.wordpress_site import WordPressSite # core model (D1)
+ from app.services.backup_policy_service import BackupPolicyError
+ site = WordPressSite.query.get(policy.target_id)
+ if not site:
+ raise BackupPolicyError('WordPress site not found')
+ app = site.application
+ if not app or not app.root_path:
+ raise BackupPolicyError('Target path not found')
+ return {
+ 'name': app.name, 'root_path': app.root_path,
+ 'site': site, 'app': app,
+ }
+
+
+def _backup_execute(policy, target, kind):
+ """Produce a WordPress backup (files + database via wp-cli). Always full."""
+ from app.services.backup_policy_service import (
+ BackupPolicyError, BackupPolicyService,
+ )
+ from .wordpress_service import WordPressService
+ result = WordPressService.backup_wordpress(target['root_path'], include_db=True)
+ if not result.get('success'):
+ raise BackupPolicyError(result.get('error') or 'WordPress backup failed')
+ storage_path = result.get('backup_path')
+ size = result.get('size') or BackupPolicyService._path_size(storage_path)
+ meta = {
+ 'kind': 'full', 'compression': 'gzip', 'incremental': False,
+ 'backup_name': result.get('backup_name'), 'includes': ['files', 'database'],
+ 'primary_archive': os.path.join(storage_path, 'files.tar.gz'),
+ }
+ return storage_path, size, meta
+
+
+def _backup_restore(policy, target, run, options):
+ """Restore a WordPress backup. 'full' (and 'tables', for now) restores
+ files + database; 'database' imports only the SQL dump; 'files' extracts
+ only the file archive."""
+ from app.services.backup_policy_service import BackupPolicyError
+ from .wordpress_service import WordPressService
+ scope = (options or {}).get('scope', 'full')
+ meta = run.get_metadata() or {}
+ backup_dir = run.storage_path
+ root = target['root_path']
+
+ if scope == 'database':
+ db_sql = os.path.join(backup_dir or '', 'database.sql')
+ if not os.path.exists(db_sql):
+ raise BackupPolicyError('Database dump not found in this backup')
+ result = WordPressService.wp_cli(root, ['db', 'import', db_sql])
+ if not result.get('success'):
+ raise BackupPolicyError(result.get('error') or 'Database restore failed')
+ return
+
+ if scope == 'files':
+ files_archive = os.path.join(backup_dir or '', 'files.tar.gz')
+ if not os.path.exists(files_archive):
+ raise BackupPolicyError('Files archive not found in this backup')
+ import tarfile
+ with tarfile.open(files_archive, 'r:gz') as tar:
+ tar.extractall(os.path.dirname(root.rstrip('/')) or '/', filter='data')
+ return
+
+ # full (or 'tables', approximated as full until per-table is implemented)
+ backup_name = meta.get('backup_name') or (os.path.basename(backup_dir) if backup_dir else None)
+ if not backup_name:
+ raise BackupPolicyError('Backup archive not found')
+ result = WordPressService.restore_backup(backup_name, root)
+ if not result.get('success'):
+ raise BackupPolicyError(result.get('error') or 'Restore failed')
+
+
+# --------------------------------------------------------------------------- #
+# Event catalog: wordpress.* types
+# --------------------------------------------------------------------------- #
+
+def _register_event_types():
+ from app.services import event_service
+ event_service.register_event_types(WP_EVENT_TYPES, source=SLUG)
+
+
+# --------------------------------------------------------------------------- #
+# Templates: 'wordpress' + 'wordpress-external-db'
+# --------------------------------------------------------------------------- #
+
+def _register_template_provider():
+ from app.services.template_service import TemplateService
+ TemplateService.register_template_provider(SLUG, validate=_validate_wp_template)
+
+
+def _validate_wp_template(template_id, variables):
+ """Provider validate hook for the WP templates.
+
+ The external-DB preflight (a live MySQL connection check before install)
+ used to be a hardcoded ``template_id == 'wordpress-external-db'`` branch in
+ core's TemplateService; it moved here with the rest of the WP coupling.
+ Returns an error dict to veto the install, or None.
+ """
+ if template_id != 'wordpress-external-db':
+ return None
+ from app.services.template_service import TemplateService
+ db_check = TemplateService.validate_mysql_connection(
+ host=variables.get('DB_HOST'),
+ port=variables.get('DB_PORT', '3306'),
+ user=variables.get('DB_USER'),
+ password=variables.get('DB_PASSWORD'),
+ database=variables.get('DB_NAME'),
+ )
+ if not db_check.get('success'):
+ return {
+ 'success': False,
+ 'error': f"Database connection failed: {db_check.get('error')}",
+ }
+ return None
diff --git a/builtin-extensions/serverkit-wordpress/plugin.json b/builtin-extensions/serverkit-wordpress/plugin.json
index 02352e80..f636d39b 100644
--- a/builtin-extensions/serverkit-wordpress/plugin.json
+++ b/builtin-extensions/serverkit-wordpress/plugin.json
@@ -42,6 +42,7 @@
"handler": "wp_ssh_import_service:run_wp_ssh_import_job"
}
],
+ "core_hooks": "core_hooks:register",
"icon": "<path d=\"M12 2a10 10 0 100 20 10 10 0 000-20zm-8 10a8 8 0 011.4-4.5l4.7 12.9A8 8 0 014 12zm8 8c-.8 0-1.6-.1-2.3-.3l2.4-7 2.5 6.8.1.1A8 8 0 0112 20zm1.1-11.8c.5 0 .9-.1.9-.1.4 0 .4-.6-.1-.6 0 0-1.4.1-2.3.1-.8 0-2.2-.1-2.2-.1-.5 0-.6.6-.1.6 0 0 .4.1.9.1l1.3 3.6-1.9 5.6L6.6 8.2c.5 0 .9-.1.9-.1.4 0 .4-.6-.1-.6 0 0-1.4.1-2.3.1h-.4A8 8 0 0112 4a8 8 0 016.5 3.3h-.3c-.8 0-1.4.7-1.4 1.5 0 .7.4 1.3.8 2 .3.6.7 1.3.7 2.3 0 .7-.3 1.6-.6 2.7l-.8 2.7-2.9-8.8z\"/>",
"contributions": {
"nav": [
diff --git a/frontend/src/plugins/plugins-manifest.json b/frontend/src/plugins/plugins-manifest.json
index dbb252cf..7b0cc876 100644
--- a/frontend/src/plugins/plugins-manifest.json
+++ b/frontend/src/plugins/plugins-manifest.json
@@ -14,7 +14,12 @@
"display_name": "WordPress",
"version": "1.0.0",
"frontend_entry": "",
- "path": "serverkit-wordpress"
+ "path": "serverkit-wordpress",
+ "styles": [
+ "plugins/serverkit-wordpress/styles/wordpress-pipeline.scss",
+ "plugins/serverkit-wordpress/styles/wordpress-plugin-library.scss",
+ "plugins/serverkit-wordpress/styles/wordpress.scss"
+ ]
}
]
}