Step 12 - completed

This commit is contained in:
2026-03-03 14:53:34 +01:00
parent 5d485b3665
commit d0b303e745
13 changed files with 950 additions and 487 deletions

View File

@@ -1,8 +1,7 @@
"""Plugin catalog registry.
"""Plugin catalog registry backed by PostgreSQL.
Maintains the authoritative list of plugins, their review status, and
aggregate install counts. Storage is in-memory until Step 12 migrates to
the ``plugins`` PostgreSQL table.
aggregate install counts. All data is persisted in the ``plugins`` table.
Module-level singleton::
@@ -11,144 +10,103 @@ Module-level singleton::
from __future__ import annotations
import copy
import time
import uuid
import json
from typing import Any, Literal
from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession
from app.models import Plugin
from app.schemas import PluginListResponse, PluginManifest
# ── Pre-seeded approved plugins (mirrors the Step 8 stub catalog) ─────
_SEED_PLUGINS: list[dict[str, Any]] = [
{
"manifest": PluginManifest(
id="plugin-github-sync",
name="GitHub Sync",
description="Sync tasks with GitHub Issues and pull requests.",
version="1.0.0",
author="Adiuva",
permissions=["read:tasks", "write:tasks"],
category="productivity",
price_cents=0,
),
"status": "approved",
"s3_package_key": "plugins/plugin-github-sync/1.0.0/package.zip",
"install_count": 0,
"avg_rating": 0.0,
"rejection_reason": None,
"submitted_at": int(time.time()),
},
{
"manifest": PluginManifest(
id="plugin-slack-notify",
name="Slack Notifier",
description="Post task and checkpoint updates to Slack channels.",
version="1.2.0",
author="Adiuva",
permissions=["read:tasks", "read:checkpoints"],
category="communication",
price_cents=499,
),
"status": "approved",
"s3_package_key": "plugins/plugin-slack-notify/1.2.0/package.zip",
"install_count": 0,
"avg_rating": 0.0,
"rejection_reason": None,
"submitted_at": int(time.time()),
},
{
"manifest": PluginManifest(
id="plugin-time-tracker",
name="Time Tracker",
description="Track time spent on tasks with automatic reporting.",
version="0.9.1",
author="Third Party",
permissions=["read:tasks", "write:tasks"],
category="productivity",
price_cents=999,
),
"status": "approved",
"s3_package_key": "plugins/plugin-time-tracker/0.9.1/package.zip",
"install_count": 0,
"avg_rating": 0.0,
"rejection_reason": None,
"submitted_at": int(time.time()),
},
]
_PAGE_SIZE = 20
def _plugin_to_manifest(p: Plugin) -> PluginManifest:
"""Convert an ORM ``Plugin`` row to a Pydantic ``PluginManifest``."""
try:
permissions = json.loads(p.permissions) if p.permissions else []
except (json.JSONDecodeError, TypeError):
permissions = []
return PluginManifest(
id=p.id,
name=p.name,
description=p.description,
version=p.version,
author=p.author_name,
permissions=permissions,
category=p.category,
price_cents=p.price_cents,
)
class PluginRegistry:
"""In-process plugin catalog.
"""PostgreSQL-backed plugin catalog.
All mutating methods are ``async`` to make the future DB swap transparent
to callers.
All methods accept an ``AsyncSession`` parameter so the calling route
controls the session lifecycle.
"""
def __init__(self) -> None:
# plugin_id → entry dict (deep-copied so each instance is independent)
self._catalog: dict[str, dict[str, Any]] = {
e["manifest"].id: copy.deepcopy(e) for e in _SEED_PLUGINS
}
# ── Queries ──────────────────────────────────────────────────────
async def list_plugins(
self,
db: AsyncSession,
category: str | None = None,
query: str | None = None,
page: int = 1,
sort: Literal["rating", "installs", "newest"] = "newest",
) -> PluginListResponse:
"""Return a page of approved plugins, optionally filtered and sorted."""
entries = [e for e in self._catalog.values() if e["status"] == "approved"]
base = select(Plugin).where(Plugin.status == "approved")
if category:
entries = [e for e in entries if e["manifest"].category == category]
base = base.where(Plugin.category == category)
if query:
q_lower = query.lower()
entries = [
e
for e in entries
if q_lower in e["manifest"].name.lower()
or q_lower in e["manifest"].description.lower()
]
pattern = f"%{query}%"
base = base.where(
Plugin.name.ilike(pattern) | Plugin.description.ilike(pattern)
)
# Count
count_q = select(func.count()).select_from(base.subquery())
total = (await db.execute(count_q)).scalar_one()
# Sort
if sort == "installs":
entries = sorted(entries, key=lambda e: e["install_count"], reverse=True)
base = base.order_by(Plugin.install_count.desc())
elif sort == "rating":
entries = sorted(entries, key=lambda e: e["avg_rating"], reverse=True)
# "newest" = catalog insertion order (dict preserves insertion in Python 3.7+)
base = base.order_by(Plugin.avg_rating.desc())
else: # newest
base = base.order_by(Plugin.created_at.desc())
total = len(entries)
start = (page - 1) * _PAGE_SIZE
page_entries = entries[start : start + _PAGE_SIZE]
base = base.offset((page - 1) * _PAGE_SIZE).limit(_PAGE_SIZE)
rows = (await db.execute(base)).scalars().all()
return PluginListResponse(
plugins=[e["manifest"] for e in page_entries],
plugins=[_plugin_to_manifest(r) for r in rows],
total=total,
page=page,
)
async def get_plugin(self, plugin_id: str) -> dict[str, Any] | None:
async def get_plugin(self, db: AsyncSession, plugin_id: str) -> dict[str, Any] | None:
"""Return ``{manifest, status, install_count, avg_rating}`` or ``None``."""
entry = self._catalog.get(plugin_id)
if entry is None:
result = await db.execute(select(Plugin).where(Plugin.id == plugin_id))
p = result.scalar_one_or_none()
if p is None:
return None
return {
"manifest": entry["manifest"],
"status": entry["status"],
"install_count": entry["install_count"],
"avg_rating": entry["avg_rating"],
"manifest": _plugin_to_manifest(p),
"status": p.status,
"install_count": p.install_count,
"avg_rating": p.avg_rating,
}
# ── Mutations ────────────────────────────────────────────────────
async def submit_plugin(
self,
db: AsyncSession,
manifest: PluginManifest,
package_s3_key: str,
) -> str:
@@ -157,54 +115,97 @@ class PluginRegistry:
Returns the plugin_id. If a plugin with the same id already exists
it is overwritten (re-submission after rejection).
"""
plugin_id = manifest.id or str(uuid.uuid4())
self._catalog[plugin_id] = {
"manifest": manifest,
"status": "pending_review",
"s3_package_key": package_s3_key,
"install_count": 0,
"avg_rating": 0.0,
"rejection_reason": None,
"submitted_at": int(time.time()),
}
plugin_id = manifest.id
existing = await db.execute(select(Plugin).where(Plugin.id == plugin_id))
row = existing.scalar_one_or_none()
if row is not None:
row.name = manifest.name
row.description = manifest.description
row.version = manifest.version
row.author_name = manifest.author
row.category = manifest.category
row.price_cents = manifest.price_cents
row.permissions = json.dumps(manifest.permissions)
row.status = "pending_review"
row.s3_package_key = package_s3_key
row.rejection_reason = None
else:
row = Plugin(
id=plugin_id,
name=manifest.name,
description=manifest.description,
version=manifest.version,
author_name=manifest.author,
category=manifest.category,
price_cents=manifest.price_cents,
permissions=json.dumps(manifest.permissions),
status="pending_review",
s3_package_key=package_s3_key,
install_count=0,
avg_rating=0.0,
)
db.add(row)
await db.commit()
return plugin_id
async def approve_plugin(self, plugin_id: str) -> None:
async def approve_plugin(self, db: AsyncSession, plugin_id: str) -> None:
"""Set *plugin_id* status to ``'approved'``.
Raises ``KeyError`` if the plugin is not found.
"""
if plugin_id not in self._catalog:
result = await db.execute(select(Plugin).where(Plugin.id == plugin_id))
row = result.scalar_one_or_none()
if row is None:
raise KeyError(f"Plugin not found: {plugin_id}")
self._catalog[plugin_id]["status"] = "approved"
self._catalog[plugin_id]["rejection_reason"] = None
row.status = "approved"
row.rejection_reason = None
await db.commit()
async def reject_plugin(self, plugin_id: str, reason: str) -> None:
async def reject_plugin(self, db: AsyncSession, plugin_id: str, reason: str) -> None:
"""Set *plugin_id* status to ``'rejected'`` and record the reason.
Raises ``KeyError`` if the plugin is not found.
"""
if plugin_id not in self._catalog:
result = await db.execute(select(Plugin).where(Plugin.id == plugin_id))
row = result.scalar_one_or_none()
if row is None:
raise KeyError(f"Plugin not found: {plugin_id}")
self._catalog[plugin_id]["status"] = "rejected"
self._catalog[plugin_id]["rejection_reason"] = reason
row.status = "rejected"
row.rejection_reason = reason
await db.commit()
async def record_install(self, plugin_id: str) -> None:
async def record_install(self, db: AsyncSession, plugin_id: str) -> None:
"""Increment the install count for *plugin_id* (no-op if not found)."""
if plugin_id in self._catalog:
self._catalog[plugin_id]["install_count"] += 1
result = await db.execute(select(Plugin).where(Plugin.id == plugin_id))
row = result.scalar_one_or_none()
if row is not None:
row.install_count = row.install_count + 1
await db.commit()
async def record_uninstall(self, plugin_id: str) -> None:
async def record_uninstall(self, db: AsyncSession, plugin_id: str) -> None:
"""Decrement the install count for *plugin_id*, floored at 0."""
if plugin_id in self._catalog:
current = self._catalog[plugin_id]["install_count"]
self._catalog[plugin_id]["install_count"] = max(0, current - 1)
result = await db.execute(select(Plugin).where(Plugin.id == plugin_id))
row = result.scalar_one_or_none()
if row is not None:
row.install_count = max(0, row.install_count - 1)
await db.commit()
# ── Internal helpers used by ReviewQueue ─────────────────────────
def _get_pending_entries(self) -> list[dict[str, Any]]:
"""Return all entries with status='pending_review' (synchronous helper)."""
return [e for e in self._catalog.values() if e["status"] == "pending_review"]
async def get_pending_entries(self, db: AsyncSession) -> list[dict[str, Any]]:
"""Return all entries with status='pending_review'."""
result = await db.execute(
select(Plugin).where(Plugin.status == "pending_review")
)
rows = result.scalars().all()
return [
{
"manifest": _plugin_to_manifest(r),
"submitted_at": int(r.submitted_at.timestamp()) if r.submitted_at else 0,
}
for r in rows
]
# Module-level singleton