Files
LogHive/backend/app/models/alert.py
T
2026-05-09 14:55:14 +08:00

72 lines
2.3 KiB
Python

"""Alert models — rules and history."""
import uuid
from datetime import datetime, timezone
from sqlalchemy import String, Integer, Float, Boolean, DateTime, Text, Enum as SAEnum
from sqlalchemy.orm import Mapped, mapped_column
import enum
from app.database import Base
class AlertLevel(str, enum.Enum):
INFO = "info"
WARNING = "warning"
CRITICAL = "critical"
class AlertOperator(str, enum.Enum):
GT = "gt"
GTE = "gte"
LT = "lt"
LTE = "lte"
EQ = "eq"
class AlertRule(Base):
__tablename__ = "alert_rules"
id: Mapped[str] = mapped_column(
String(36), primary_key=True, default=lambda: str(uuid.uuid4())
)
project_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
name: Mapped[str] = mapped_column(String(128), nullable=False)
level: Mapped[AlertLevel] = mapped_column(
SAEnum(AlertLevel), default=AlertLevel.WARNING
)
field: Mapped[str] = mapped_column(
String(64), nullable=False, default="level"
) # log field to evaluate
operator: Mapped[AlertOperator] = mapped_column(
SAEnum(AlertOperator), default=AlertOperator.GTE
)
threshold: Mapped[float] = mapped_column(Float, nullable=False)
window_minutes: Mapped[int] = mapped_column(Integer, default=5)
is_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
notify_channels: Mapped[str] = mapped_column(
String(256), default=""
) # comma-separated
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)
class AlertHistory(Base):
__tablename__ = "alert_history"
id: Mapped[str] = mapped_column(
String(36), primary_key=True, default=lambda: str(uuid.uuid4())
)
rule_id: Mapped[str] = mapped_column(
String(36), nullable=False, index=True
)
project_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
level: Mapped[AlertLevel] = mapped_column(SAEnum(AlertLevel))
message: Mapped[str] = mapped_column(Text, nullable=False)
triggered_value: Mapped[float] = mapped_column(Float, nullable=True)
is_acknowledged: Mapped[bool] = mapped_column(Boolean, default=False)
triggered_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)