gate: fix worker on_startup to set tenant context per-tenant for plugin activation

This commit is contained in:
Agent Zero
2026-07-31 09:09:23 +02:00
parent 1a980ba9d8
commit 5ce85f4324
+30 -14
View File
@@ -118,6 +118,16 @@ async def on_startup(ctx: dict[str, Any]) -> None:
async_session = async_sessionmaker(get_engine(), expire_on_commit=False) async_session = async_sessionmaker(get_engine(), expire_on_commit=False)
# Activate plugins that are marked active in DB (register event handlers) # Activate plugins that are marked active in DB (register event handlers)
# RLS fail-closed requires tenant context for tenant-table writes
from app.models.tenant import Tenant as TenantModel
from app.core.db import set_tenant_context
async with async_session() as db:
# Load all tenant IDs for per-tenant plugin activation
tenant_result = await db.execute(sa_select(TenantModel.id))
all_tenant_ids = [row[0] for row in tenant_result]
logger.info(f"Worker: loaded {len(all_tenant_ids)} tenants for plugin activation")
async with async_session() as db: async with async_session() as db:
for name in registry.resolve_load_order(): for name in registry.resolve_load_order():
plugin = registry.get_plugin(name) plugin = registry.get_plugin(name)
@@ -129,21 +139,27 @@ async def on_startup(ctx: dict[str, Any]) -> None:
plugin_record = result.scalar_one_or_none() plugin_record = result.scalar_one_or_none()
if plugin_record is None or not plugin_record.active: if plugin_record is None or not plugin_record.active:
continue continue
try: # Activate plugin per-tenant with tenant context set
await plugin.on_activate(db, container, event_bus) activation_failed = False
logger.info(f"Worker: activated plugin {name}") for tenant_id in all_tenant_ids:
except Exception as exc:
logger.error(f"Worker: failed to activate plugin {name}: {exc}")
# Report worker startup errors to Forgejo
try: try:
from app.plugins.builtins.forgejo_error_reporter.service import report_error_to_forgejo await set_tenant_context(db, tenant_id)
await report_error_to_forgejo({ await plugin.on_activate(db, container, event_bus)
"message": f"[Worker] Plugin activation failed: {name}: {exc}", except Exception as exc:
"stack": traceback.format_exc(), logger.error(f"Worker: failed to activate plugin {name} for tenant {tenant_id}: {exc}")
"context": {"plugin": name, "source": "worker_startup"}, activation_failed = True
}) try:
except Exception: from app.plugins.builtins.forgejo_error_reporter.service import report_error_to_forgejo
pass await report_error_to_forgejo({
"message": f"[Worker] Plugin activation failed: {name}: {exc}",
"stack": traceback.format_exc(),
"context": {"plugin": name, "source": "worker_startup"},
})
except Exception:
pass
break
if not activation_failed:
logger.info(f"Worker: activated plugin {name}")
await db.commit() await db.commit()
# Register webhook dispatcher on the event bus # Register webhook dispatcher on the event bus