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
+19 -3
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,12 +139,15 @@ 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
# Activate plugin per-tenant with tenant context set
activation_failed = False
for tenant_id in all_tenant_ids:
try: try:
await set_tenant_context(db, tenant_id)
await plugin.on_activate(db, container, event_bus) await plugin.on_activate(db, container, event_bus)
logger.info(f"Worker: activated plugin {name}")
except Exception as exc: except Exception as exc:
logger.error(f"Worker: failed to activate plugin {name}: {exc}") logger.error(f"Worker: failed to activate plugin {name} for tenant {tenant_id}: {exc}")
# Report worker startup errors to Forgejo activation_failed = True
try: try:
from app.plugins.builtins.forgejo_error_reporter.service import report_error_to_forgejo from app.plugins.builtins.forgejo_error_reporter.service import report_error_to_forgejo
await report_error_to_forgejo({ await report_error_to_forgejo({
@@ -144,6 +157,9 @@ async def on_startup(ctx: dict[str, Any]) -> None:
}) })
except Exception: except Exception:
pass 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