Files
checkbot/app/runtime.py
T

48 lines
1.8 KiB
Python

import asyncio
import time
from contextlib import asynccontextmanager
from fastapi import FastAPI
from .alerts import AlertAnalyzer, AlertPipeline, AlertRepository, SlidingWindowLimiter
from .chat import AdapterRegistry
from .constants import ALERTS_BUNDLE_SECONDS, DEFAULT_BUNDLE_SECONDS
from .db import Database
from .mutes import MuteService
from .ollama import OllamaClient
from .poller import Poller, PollerStatus, StateStore
from .routing import RouteService
class Runtime:
def __init__(self, db: Database, store):
self.status = PollerStatus()
self.alerts = AlertRepository(db)
self.state = StateStore(db)
self.registry = AdapterRegistry(store)
self.mutes = MuteService(db)
self.routes = RouteService(db)
analyzer = AlertAnalyzer(store, lambda: OllamaClient.from_settings(store),
self.state.recent_changes, SlidingWindowLimiter(time.time))
self.pipeline = AlertPipeline(
self.alerts, self.registry.current, analyzer,
lambda: store.get_int(ALERTS_BUNDLE_SECONDS, DEFAULT_BUNDLE_SECONDS),
routes=self.routes, mutes=self.mutes,
)
self.poller = Poller(store, self.state, self.pipeline.handle, self.status)
@asynccontextmanager
async def lifespan(self, app: FastAPI):
poller_task = asyncio.create_task(self.poller.run())
pipeline_task = asyncio.create_task(self.pipeline.run())
try:
yield
finally:
poller_task.cancel()
await asyncio.gather(poller_task, return_exceptions=True)
await self.pipeline.finish()
pipeline_task.cancel()
await asyncio.gather(pipeline_task, return_exceptions=True)
await self.pipeline.aclose()
await self.registry.aclose()