Files
ServerKit/backend/app/plugins_sdk/__init__.py
T
Juan DenisandClaude Opus 4.8 8428326a26 feat(jobs): unified background-job orchestration on the Queue Bus
Generalize the Notification Bus pattern (thin {id} message -> fat DB row
-> single consumer) into a Job/WorkUnit layer on top of the Queue Bus, so
background work flows through one pipe instead of many ad-hoc threads.

- app/jobs: Job + ScheduledJob models, handler registry, JobService +
  ScheduledJobService, one generic JobConsumer, one JobScheduler ticker,
  and a plugin SDK surface (app.plugins_sdk.jobs).
- Migrate the 8 per-domain daemon scheduler threads (auto-sync,
  snapshot-retention, workflow, health-check, wp-update, api-background,
  pairing-prune, registrar-expiry) to ScheduledJob rows + built-in
  handlers that reuse the exact prior check functions: cadence and
  per-task de-dup unchanged, only the trigger moved.
- Retire the orphaned in-memory BackgroundJobService; repoint
  /api/v1/performance/jobs at JobService.
- Add /api/v1/jobs (list/get/cancel/retry/stats; scheduled list/run/
  toggle) as a single pane over all background work.
- tests/test_jobs.py: enqueue->run->succeed, dead-letter->failed,
  unknown-kind, cancel, retry, scheduler tick/advance, built-ins.

No Alembic migration (tables created via create_all), avoiding a
multi-head clash with the in-flight telemetry work. Plan lives in
docs/ORCHESTRATION_ROADMAP.md (local/git-ignored).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 20:44:12 -04:00

113 lines
3.0 KiB
Python

"""
ServerKit Backend Plugin SDK.
Plugins should depend on names re-exported here rather than reaching into
host internals directly. As long as this surface stays stable, host-side
refactors don't break installed plugins.
Typical plugin module:
from flask import Blueprint, request, jsonify
from app.plugins_sdk import (
db, jwt_required, current_user, audit, logger,
)
my_bp = Blueprint('my_plugin', __name__)
log = logger(__name__)
@my_bp.route('/things', methods=['GET'])
@jwt_required()
def list_things():
user = current_user()
# ... do work, use db.session, etc ...
return jsonify({'ok': True})
The lifecycle hook contract (called by plugin_service when installing /
uninstalling): a single positional arg — the InstalledPlugin row.
# In plugins/<slug>/lifecycle.py
from app.plugins_sdk import db, logger
log = logger(__name__)
def on_install(plugin):
log.info(f'Setting up {plugin.slug}')
def on_uninstall(plugin):
log.info(f'Tearing down {plugin.slug}')
"""
import logging
from app import db, jwt
from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt
def current_user():
"""Return the current authenticated user, or None if no JWT context.
Resolves the JWT identity (a stringified user id, per the host's
@jwt.user_identity_loader) into a User row.
"""
try:
uid = get_jwt_identity()
except Exception:
return None
if uid is None:
return None
from app.models.user import User
try:
return User.query.get(int(uid))
except (TypeError, ValueError):
return None
def logger(name):
"""Return a logger scoped to a plugin module name."""
return logging.getLogger(name)
def audit(action, target_type, target_id=None, details=None, user_id=None):
"""Write an audit log entry from a plugin.
Thin wrapper around AuditService so plugins don't have to know its
import path. `user_id` defaults to the current authenticated user.
"""
if user_id is None:
u = current_user()
user_id = u.id if u else None
from app.services.audit_service import AuditService
return AuditService.log(
action=action,
user_id=user_id,
target_type=target_type,
target_id=target_id,
details=details or {},
)
# AI extension SDK — plugins do `from app.plugins_sdk import ai` then register
# tools/context against the core assistant (see plugins_sdk/ai.py). Imported
# lazily-safe: ai.py only depends on the AI tool registry, not on a running app.
from app.plugins_sdk import ai
from app.queue_bus.sdk import QueueBusSdk
from app.notifications.sdk import NotifySdk
from app.jobs.sdk import JobsSdk
queue = QueueBusSdk()
notify = NotifySdk()
jobs = JobsSdk()
__all__ = [
'db',
'jwt',
'jwt_required',
'get_jwt_identity',
'get_jwt',
'current_user',
'logger',
'audit',
'ai',
'queue',
'notify',
'jobs',
]