Files
checkbot/app/runtime.py
T

54 lines
2.2 KiB
Python

import asyncio
import time
from contextlib import asynccontextmanager
from fastapi import FastAPI
from .alerts import AlertActions, AlertAnalyzer, AlertPipeline, AlertRepository, SlidingWindowLimiter
from .chat import AdapterRegistry
from .chatops import ChatOps
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, actions=AlertActions(store),
)
self.poller = Poller(store, self.state, self.pipeline.handle, self.status)
self.chatops = ChatOps(db, store, self.state, self.alerts, self.mutes)
@asynccontextmanager
async def lifespan(self, app: FastAPI):
poller_task = asyncio.create_task(self.poller.run())
pipeline_task = asyncio.create_task(self.pipeline.run())
listener_tasks = [asyncio.create_task(run()) for run in self.chatops.listener_runners()]
try:
yield
finally:
for task in listener_tasks:
task.cancel()
await asyncio.gather(*listener_tasks, return_exceptions=True)
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()