Files
leocrm/app/core/event_bus.py
T
leocrm-bot 851e7999ba T09: KI-Copilot API + Hybrid Workflow Engine + LLM client + event-triggered workflows
- KI-Copilot: NL query → proposed actions, execute with RBAC, history, audit logging
- LLM client: mock mode (no API key) + OpenAI-compatible mode (AI_MODEL/AI_API_KEY)
- Action mapper: NL intent → API calls (create/update/delete/search company/contact)
- Workflow engine: step types (action/approval/notification/condition), JSONB steps
- Workflow lifecycle: pending → in_progress → completed/rejected/cancelled
- Event-triggered workflows: event bus → auto-start instances
- Code-engine workflows: onboarding on user.created event
- Approval timeout: auto-reject after configured hours
- 5 new tenant-scoped tables with RLS: ai_conversations, ai_messages, workflows, workflow_instances, workflow_step_history
- Migration 0004: all tables + RLS policies + tenant_id + indexes
- 238 tests pass (30 AC + 105 coverage + 103 existing), 84.12% T09 module coverage
- MissingGreenlet fix: safe accessor helpers for async ORM attribute access
2026-06-29 08:02:15 +02:00

52 lines
1.7 KiB
Python

"""In-process event bus for publish/subscribe."""
from __future__ import annotations
import asyncio
from collections import defaultdict
from typing import Any, Callable, Coroutine
EventHandler = Callable[[dict[str, Any]], Coroutine[Any, Any, None]]
class EventBus:
"""Simple async event bus for in-process pub/sub."""
def __init__(self) -> None:
self._handlers: dict[str, list[EventHandler]] = defaultdict(list)
def subscribe(self, event_name: str, handler: EventHandler) -> None:
"""Subscribe a handler to an event."""
self._handlers[event_name].append(handler)
def unsubscribe(self, event_name: str, handler: EventHandler) -> None:
"""Unsubscribe a handler from an event."""
if event_name in self._handlers:
self._handlers[event_name] = [h for h in self._handlers[event_name] if h is not handler]
async def publish(self, event_name: str, payload: dict[str, Any]) -> None:
"""Publish an event to all subscribers."""
handlers = self._handlers.get(event_name, [])
tasks = [asyncio.create_task(h(payload)) for h in handlers]
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
# Global event bus instance
_event_bus = EventBus()
def get_event_bus() -> EventBus:
"""Get the global event bus."""
return _event_bus
def register_workflow_event_handlers() -> None:
"""Register workflow event handlers on the global event bus.
Subscribes to events that can trigger workflows (user.created, etc.).
Should be called during application startup.
"""
from app.workflows.engine import register_workflow_event_handlers as _register
_register()