The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
feat: added notifications
dduxd0acecfd035f
diff --git a/backend/app/controllers/clientcontrollers/client.controller.go b/backend/app/controllers/clientcontrollers/client.controller.goindex 500a75ee..7022f2b3 100644--- a/backend/app/controllers/clientcontrollers/client.controller.go+++ b/backend/app/controllers/clientcontrollers/client.controller.go@@ -190,14 +190,21 @@ func (e clientController) Report(c *gin.Context) {return}+ var exceptionHashes []string+ for _, est := range exceptionStackTraceToInsert {+ exceptionHashes = append(exceptionHashes, est.ExceptionHash)+ }+if project, exists := c.Get(middleware.ProjectContextKey); exists {if p, ok := project.(*models.Project); ok && p.OrganizationId != nil {hooks.BroadcastReport(hooks.ReportEvent{- OrganizationId: *p.OrganizationId,- EndpointCount: len(endpointsToInsert),- ErrorCount: len(exceptionStackTraceToInsert),- TaskCount: len(tasksToInsert),- RecordingCount: len(recordingsWork),+ OrganizationId: *p.OrganizationId,+ ProjectId: projectId,+ EndpointCount: len(endpointsToInsert),+ ErrorCount: len(exceptionStackTraceToInsert),+ TaskCount: len(tasksToInsert),+ RecordingCount: len(recordingsWork),+ ExceptionHashes: exceptionHashes,})}}diff --git a/backend/app/controllers/notification_channel.controller.go b/backend/app/controllers/notification_channel.controller.gonew file mode 100644index 00000000..2e64a7bc--- /dev/null+++ b/backend/app/controllers/notification_channel.controller.go@@ -0,0 +1,264 @@+package controllers++import (+ "database/sql"+ "encoding/json"+ "net/http"+ "strconv"+ "strings"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/notifications"+ "github.com/tracewayapp/traceway/backend/app/repositories"+ traceway "go.tracewayapp.com"+)++type notificationChannelController struct{}++func (ctrl *notificationChannelController) List(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ tx := middleware.GetTx(ctx)+ channels, err := repositories.NotificationChannelRepository.FindByProject(tx, projectId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list notification channels: %w", err))+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"channels": channels})+}++type createChannelRequest struct {+ Name string `json:"name"`+ ChannelType string `json:"channelType"`+ Config json.RawMessage `json:"config"`+}++var validChannelTypes = map[string]bool{+ "email": true, "webhook": true, "slack": true, "github": true,+}++func (ctrl *notificationChannelController) Create(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ var req createChannelRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ req.Name = strings.TrimSpace(req.Name)+ if req.Name == "" {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Name is required."})+ return+ }+ if len(req.Name) > 200 {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Name must be 200 characters or fewer."})+ return+ }+ if !validChannelTypes[req.ChannelType] {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Channel type must be one of: email, webhook, slack, github."})+ return+ }++ adapter, err := notifications.NewAdapter(req.ChannelType, req.Config)+ if err != nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})+ return+ }+ if err := adapter.Validate(); err != nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})+ return+ }++ userId := middleware.GetUserId(ctx)+ var createdBy *int+ if userId > 0 {+ createdBy = &userId+ }++ tx := middleware.GetTx(ctx)+ now := time.Now().UTC()+ channel := &models.NotificationChannel{+ ProjectId: projectId,+ Name: req.Name,+ ChannelType: req.ChannelType,+ Config: req.Config,+ Enabled: true,+ CreatedBy: createdBy,+ CreatedAt: now,+ UpdatedAt: now,+ }++ id, err := repositories.NotificationChannelRepository.Create(tx, channel)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to create notification channel: %w", err))+ return+ }+ channel.Id = id++ ctx.JSON(http.StatusCreated, channel)+}++func (ctrl *notificationChannelController) Update(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ idStr := ctx.Param("id")+ id, err := strconv.Atoi(idStr)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid channel id"})+ return+ }++ var req createChannelRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ req.Name = strings.TrimSpace(req.Name)+ if req.Name == "" {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Name is required."})+ return+ }+ if len(req.Name) > 200 {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Name must be 200 characters or fewer."})+ return+ }+ if !validChannelTypes[req.ChannelType] {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Channel type must be one of: email, webhook, slack, github."})+ return+ }++ adapter, err := notifications.NewAdapter(req.ChannelType, req.Config)+ if err != nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})+ return+ }+ if err := adapter.Validate(); err != nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})+ return+ }++ tx := middleware.GetTx(ctx)+ existing, err := repositories.NotificationChannelRepository.FindById(tx, id)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification channel: %w", err))+ return+ }+ if existing == nil || existing.ProjectId != projectId {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})+ return+ }++ existing.Name = req.Name+ existing.ChannelType = req.ChannelType+ existing.Config = req.Config+ existing.UpdatedAt = time.Now().UTC()++ if err := repositories.NotificationChannelRepository.Update(tx, existing); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update notification channel: %w", err))+ return+ }++ ctx.JSON(http.StatusOK, existing)+}++func (ctrl *notificationChannelController) Delete(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ idStr := ctx.Param("id")+ id, err := strconv.Atoi(idStr)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid channel id"})+ return+ }++ tx := middleware.GetTx(ctx)+ existing, err := repositories.NotificationChannelRepository.FindById(tx, id)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete notification channel: %w", err))+ return+ }+ if existing == nil || existing.ProjectId != projectId {+ ctx.JSON(http.StatusOK, gin.H{"deleted": true})+ return+ }++ if err := repositories.NotificationChannelRepository.Delete(tx, id); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete notification channel: %w", err))+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"deleted": true})+}++func (ctrl *notificationChannelController) Test(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ idStr := ctx.Param("id")+ id, err := strconv.Atoi(idStr)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid channel id"})+ return+ }++ channel, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.NotificationChannel, error) {+ return repositories.NotificationChannelRepository.FindById(tx, id)+ })+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification channel: %w", err))+ return+ }+ if channel == nil || channel.ProjectId != projectId {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})+ return+ }++ adapter, err := notifications.NewAdapter(channel.ChannelType, channel.Config)+ if err != nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})+ return+ }++ testMsg := notifications.Message{+ Subject: "Traceway Test Notification",+ Body: "This is a test notification from Traceway. If you received this, your notification channel is configured correctly.",+ Severity: notifications.SeverityInfo,+ RuleType: "test",+ RuleName: "Test",+ }++ if err := adapter.Send(ctx.Request.Context(), testMsg); err != nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"success": true})+}++var NotificationChannelController = notificationChannelController{}diff --git a/backend/app/controllers/notification_history.controller.go b/backend/app/controllers/notification_history.controller.gonew file mode 100644index 00000000..d95edfe5--- /dev/null+++ b/backend/app/controllers/notification_history.controller.go@@ -0,0 +1,73 @@+package controllers++import (+ "database/sql"+ "net/http"++ "github.com/gin-gonic/gin"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories"+ traceway "go.tracewayapp.com"+)++type notificationHistoryController struct{}++type NotificationHistorySearchRequest struct {+ Pagination PaginationParams `json:"pagination"`+ Search string `json:"search"`+}++func (ctrl *notificationHistoryController) List(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ var request NotificationHistorySearchRequest+ if err := ctx.ShouldBindJSON(&request); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ page := request.Pagination.Page+ pageSize := request.Pagination.PageSize++ type historyResult struct {+ Items []*models.NotificationHistory+ Total int64+ }++ result, err := db.ExecuteTransaction(func(tx *sql.Tx) (historyResult, error) {+ items, total, err := repositories.NotificationHistoryRepository.FindByProject(tx, projectId, page, pageSize, request.Search)+ return historyResult{Items: items, Total: total}, err+ })+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list notification history: %w", err))+ return+ }++ totalPages := result.Total / int64(pageSize)+ if result.Total%int64(pageSize) != 0 {+ totalPages+++ }++ data := result.Items+ if data == nil {+ data = []*models.NotificationHistory{}+ }++ ctx.JSON(http.StatusOK, PaginatedResponse[*models.NotificationHistory]{+ Data: data,+ Pagination: Pagination{+ Page: page,+ PageSize: pageSize,+ Total: result.Total,+ TotalPages: totalPages,+ },+ })+}++var NotificationHistoryController = notificationHistoryController{}diff --git a/backend/app/controllers/notification_rule.controller.go b/backend/app/controllers/notification_rule.controller.gonew file mode 100644index 00000000..cdbf4d8f--- /dev/null+++ b/backend/app/controllers/notification_rule.controller.go@@ -0,0 +1,333 @@+package controllers++import (+ "encoding/json"+ "net/http"+ "strconv"+ "strings"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories"+ traceway "go.tracewayapp.com"+)++type notificationRuleController struct{}++var validRuleTypes = map[string]bool{+ "error_rate_threshold": true,+ "endpoint_p95_threshold": true,+ "endpoint_p99_threshold": true,+ "apdex_drop": true,+ "metric_threshold": true,+ "no_data": true,+ "error_count_threshold": true,+ "task_duration_threshold": true,+ "task_failure_rate": true,+ "throughput_drop": true,+ "endpoint_error_rate": true,+ "new_error": true,+ "error_regression": true,+ "impact_score_critical": true,+ "impact_score_high": true,+ "impact_score_medium": true,+}++func (ctrl *notificationRuleController) List(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ tx := middleware.GetTx(ctx)+ rules, err := repositories.NotificationRuleRepository.FindByProjectWithChannel(tx, projectId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list notification rules: %w", err))+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"rules": rules})+}++type createRuleRequest struct {+ ChannelId int `json:"channelId"`+ Name string `json:"name"`+ RuleType string `json:"ruleType"`+ Config json.RawMessage `json:"config"`+ CooldownMinutes int `json:"cooldownMinutes"`+}++func (ctrl *notificationRuleController) Create(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ var req createRuleRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ req.Name = strings.TrimSpace(req.Name)+ if req.Name == "" {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Name is required."})+ return+ }+ if len(req.Name) > 200 {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Name must be 200 characters or fewer."})+ return+ }+ if !validRuleTypes[req.RuleType] {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Invalid rule type."})+ return+ }+ if req.CooldownMinutes < 0 {+ req.CooldownMinutes = 15+ }++ tx := middleware.GetTx(ctx)++ channel, err := repositories.NotificationChannelRepository.FindById(tx, req.ChannelId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification channel: %w", err))+ return+ }+ if channel == nil || channel.ProjectId != projectId {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Channel not found in this project."})+ return+ }++ userId := middleware.GetUserId(ctx)+ var createdBy *int+ if userId > 0 {+ createdBy = &userId+ }++ now := time.Now().UTC()+ cooldown := req.CooldownMinutes+ if cooldown == 0 {+ cooldown = 15+ }+ rule := &models.NotificationRule{+ ProjectId: projectId,+ ChannelId: req.ChannelId,+ Name: req.Name,+ RuleType: req.RuleType,+ Config: req.Config,+ Enabled: true,+ CooldownMinutes: cooldown,+ CreatedBy: createdBy,+ CreatedAt: now,+ UpdatedAt: now,+ }++ id, err := repositories.NotificationRuleRepository.Create(tx, rule)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to create notification rule: %w", err))+ return+ }+ rule.Id = id++ ctx.JSON(http.StatusCreated, rule)+}++func (ctrl *notificationRuleController) Update(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ idStr := ctx.Param("id")+ id, err := strconv.Atoi(idStr)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid rule id"})+ return+ }++ var req createRuleRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ req.Name = strings.TrimSpace(req.Name)+ if req.Name == "" {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Name is required."})+ return+ }+ if len(req.Name) > 200 {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Name must be 200 characters or fewer."})+ return+ }+ if !validRuleTypes[req.RuleType] {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Invalid rule type."})+ return+ }++ tx := middleware.GetTx(ctx)++ existing, err := repositories.NotificationRuleRepository.FindById(tx, id)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification rule: %w", err))+ return+ }+ if existing == nil || existing.ProjectId != projectId {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "rule not found"})+ return+ }++ channel, err := repositories.NotificationChannelRepository.FindById(tx, req.ChannelId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification channel: %w", err))+ return+ }+ if channel == nil || channel.ProjectId != projectId {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Channel not found in this project."})+ return+ }++ cooldown := req.CooldownMinutes+ if cooldown <= 0 {+ cooldown = 15+ }++ existing.ChannelId = req.ChannelId+ existing.Name = req.Name+ existing.RuleType = req.RuleType+ existing.Config = req.Config+ existing.CooldownMinutes = cooldown+ existing.UpdatedAt = time.Now().UTC()++ if err := repositories.NotificationRuleRepository.Update(tx, existing); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update notification rule: %w", err))+ return+ }++ ctx.JSON(http.StatusOK, existing)+}++func (ctrl *notificationRuleController) Delete(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ idStr := ctx.Param("id")+ id, err := strconv.Atoi(idStr)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid rule id"})+ return+ }++ tx := middleware.GetTx(ctx)+ existing, err := repositories.NotificationRuleRepository.FindById(tx, id)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete notification rule: %w", err))+ return+ }+ if existing == nil || existing.ProjectId != projectId {+ ctx.JSON(http.StatusOK, gin.H{"deleted": true})+ return+ }++ if err := repositories.NotificationRuleRepository.Delete(tx, id); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete notification rule: %w", err))+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"deleted": true})+}++func (ctrl *notificationRuleController) Toggle(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ idStr := ctx.Param("id")+ id, err := strconv.Atoi(idStr)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid rule id"})+ return+ }++ tx := middleware.GetTx(ctx)+ existing, err := repositories.NotificationRuleRepository.FindById(tx, id)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification rule: %w", err))+ return+ }+ if existing == nil || existing.ProjectId != projectId {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "rule not found"})+ return+ }++ newEnabled := !existing.Enabled+ if err := repositories.NotificationRuleRepository.UpdateEnabled(tx, id, newEnabled); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to toggle notification rule: %w", err))+ return+ }++ existing.Enabled = newEnabled+ ctx.JSON(http.StatusOK, existing)+}++type snoozeRequest struct {+ DurationMinutes int `json:"durationMinutes"`+}++func (ctrl *notificationRuleController) Snooze(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ idStr := ctx.Param("id")+ id, err := strconv.Atoi(idStr)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid rule id"})+ return+ }++ var req snoozeRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ tx := middleware.GetTx(ctx)+ existing, err := repositories.NotificationRuleRepository.FindById(tx, id)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification rule: %w", err))+ return+ }+ if existing == nil || existing.ProjectId != projectId {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "rule not found"})+ return+ }++ var snoozedUntil *time.Time+ if req.DurationMinutes > 0 {+ t := time.Now().UTC().Add(time.Duration(req.DurationMinutes) * time.Minute)+ snoozedUntil = &t+ }++ if err := repositories.NotificationRuleRepository.UpdateSnoozedUntil(tx, id, snoozedUntil); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to snooze notification rule: %w", err))+ return+ }++ existing.SnoozedUntil = snoozedUntil+ ctx.JSON(http.StatusOK, existing)+}++var NotificationRuleController = notificationRuleController{}diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.goindex 564f61a0..6c51eea5 100644--- a/backend/app/controllers/routes.go+++ b/backend/app/controllers/routes.go@@ -128,6 +128,24 @@ func RegisterControllers(router *gin.RouterGroup) {router.POST("/projects/source-map-token", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, ProjectController.GenerateSourceMapToken)router.POST("/sourcemaps/upload", middleware.UseSourceMapAuth, SourceMapController.Upload)+ // Notification channels+ router.GET("/notification-channels", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.Transactional, NotificationChannelController.List)+ router.POST("/notification-channels", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, NotificationChannelController.Create)+ router.PUT("/notification-channels/:id", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, NotificationChannelController.Update)+ router.DELETE("/notification-channels/:id", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, NotificationChannelController.Delete)+ router.POST("/notification-channels/:id/test", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, NotificationChannelController.Test)++ // Notification rules+ router.GET("/notification-rules", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.Transactional, NotificationRuleController.List)+ router.POST("/notification-rules", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, NotificationRuleController.Create)+ router.PUT("/notification-rules/:id", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, NotificationRuleController.Update)+ router.DELETE("/notification-rules/:id", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, NotificationRuleController.Delete)+ router.POST("/notification-rules/:id/toggle", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, NotificationRuleController.Toggle)+ router.POST("/notification-rules/:id/snooze", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, NotificationRuleController.Snooze)++ // Notification history+ router.POST("/notification-history", middleware.UseAppAuth, middleware.RequireProjectAccess, NotificationHistoryController.List)+for _, register := range ExtensionRoutes {register(router)}diff --git a/backend/app/hooks/report_hooks.go b/backend/app/hooks/report_hooks.goindex c43a2302..c6426722 100644--- a/backend/app/hooks/report_hooks.go+++ b/backend/app/hooks/report_hooks.go@@ -1,13 +1,19 @@package hooks-import "sync"+import (+ "sync"++ "github.com/google/uuid"+)type ReportEvent struct {- OrganizationId int- EndpointCount int- ErrorCount int- TaskCount int- RecordingCount int+ OrganizationId int+ ProjectId uuid.UUID+ EndpointCount int+ ErrorCount int+ TaskCount int+ RecordingCount int+ ExceptionHashes []string}var (diff --git a/backend/app/migrations/ch/0037_create_fired_notifications.up.sql b/backend/app/migrations/ch/0037_create_fired_notifications.up.sqlnew file mode 100644index 00000000..c6347fc9--- /dev/null+++ b/backend/app/migrations/ch/0037_create_fired_notifications.up.sql@@ -0,0 +1,18 @@+CREATE TABLE IF NOT EXISTS fired_notifications (+ id UUID DEFAULT generateUUIDv4(),+ project_id UUID,+ rule_id Int32,+ rule_type String,+ rule_name String,+ channel_type String,+ channel_name String,+ severity String,+ subject String,+ body String,+ status String DEFAULT 'sent',+ error_message String DEFAULT '',+ endpoint String DEFAULT '',+ fired_at DateTime64(3) DEFAULT now64(3)+) ENGINE = MergeTree()+PARTITION BY toYYYYMM(fired_at)+ORDER BY (project_id, fired_at)diff --git a/backend/app/migrations/pg/0021_create_notification_channels.up.sql b/backend/app/migrations/pg/0021_create_notification_channels.up.sqlnew file mode 100644index 00000000..debc88cf--- /dev/null+++ b/backend/app/migrations/pg/0021_create_notification_channels.up.sql@@ -0,0 +1,11 @@+CREATE TABLE IF NOT EXISTS notification_channels (+ id SERIAL PRIMARY KEY,+ project_id UUID NOT NULL REFERENCES projects(id),+ name VARCHAR(200) NOT NULL,+ channel_type VARCHAR(50) NOT NULL,+ config JSONB NOT NULL DEFAULT '{}',+ enabled BOOLEAN NOT NULL DEFAULT true,+ created_by INTEGER REFERENCES users(id),+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);diff --git a/backend/app/migrations/pg/0022_create_notification_channels_project_idx.up.sql b/backend/app/migrations/pg/0022_create_notification_channels_project_idx.up.sqlnew file mode 100644index 00000000..21134a55--- /dev/null+++ b/backend/app/migrations/pg/0022_create_notification_channels_project_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX idx_notification_channels_project ON notification_channels(project_id);diff --git a/backend/app/migrations/pg/0023_create_notification_rules.up.sql b/backend/app/migrations/pg/0023_create_notification_rules.up.sqlnew file mode 100644index 00000000..6f72c3d4--- /dev/null+++ b/backend/app/migrations/pg/0023_create_notification_rules.up.sql@@ -0,0 +1,14 @@+CREATE TABLE IF NOT EXISTS notification_rules (+ id SERIAL PRIMARY KEY,+ project_id UUID NOT NULL REFERENCES projects(id),+ channel_id INTEGER NOT NULL REFERENCES notification_channels(id) ON DELETE CASCADE,+ name VARCHAR(200) NOT NULL,+ rule_type VARCHAR(50) NOT NULL,+ config JSONB NOT NULL DEFAULT '{}',+ enabled BOOLEAN NOT NULL DEFAULT true,+ cooldown_minutes INTEGER NOT NULL DEFAULT 15,+ snoozed_until TIMESTAMPTZ,+ created_by INTEGER REFERENCES users(id),+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);diff --git a/backend/app/migrations/pg/0024_create_notification_rules_project_idx.up.sql b/backend/app/migrations/pg/0024_create_notification_rules_project_idx.up.sqlnew file mode 100644index 00000000..40d27ad2--- /dev/null+++ b/backend/app/migrations/pg/0024_create_notification_rules_project_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX idx_notification_rules_project ON notification_rules(project_id);diff --git a/backend/app/migrations/pg/0025_create_notification_history.up.sql b/backend/app/migrations/pg/0025_create_notification_history.up.sqlnew file mode 100644index 00000000..3f3e561f--- /dev/null+++ b/backend/app/migrations/pg/0025_create_notification_history.up.sql@@ -0,0 +1,15 @@+CREATE TABLE IF NOT EXISTS notification_history (+ id SERIAL PRIMARY KEY,+ project_id UUID NOT NULL REFERENCES projects(id),+ rule_id INTEGER REFERENCES notification_rules(id) ON DELETE SET NULL,+ channel_id INTEGER REFERENCES notification_channels(id) ON DELETE SET NULL,+ rule_type VARCHAR(50) NOT NULL,+ rule_name VARCHAR(200) NOT NULL,+ channel_name VARCHAR(200) NOT NULL,+ severity VARCHAR(20) NOT NULL,+ subject TEXT NOT NULL,+ body TEXT NOT NULL,+ status VARCHAR(20) NOT NULL DEFAULT 'sent',+ error_message TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);diff --git a/backend/app/migrations/pg/0026_create_notification_history_indexes.up.sql b/backend/app/migrations/pg/0026_create_notification_history_indexes.up.sqlnew file mode 100644index 00000000..6d612f97--- /dev/null+++ b/backend/app/migrations/pg/0026_create_notification_history_indexes.up.sql@@ -0,0 +1 @@+CREATE INDEX idx_notification_history_project_created ON notification_history(project_id, created_at DESC);diff --git a/backend/app/migrations/pg/0027_create_notification_rules_channel_idx.up.sql b/backend/app/migrations/pg/0027_create_notification_rules_channel_idx.up.sqlnew file mode 100644index 00000000..683df14b--- /dev/null+++ b/backend/app/migrations/pg/0027_create_notification_rules_channel_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX idx_notification_rules_channel ON notification_rules(channel_id);diff --git a/backend/app/models/models.go b/backend/app/models/models.goindex 1f5f8123..00f52b5a 100644--- a/backend/app/models/models.go+++ b/backend/app/models/models.go@@ -26,6 +26,10 @@ func Init(driver lit.Driver) {lit.RegisterModelWithNaming[MetricRegistry](driver, metricRegistryNaming{})lit.RegisterModel[WidgetGroup](driver)lit.RegisterModel[WidgetGroupWidget](driver)+ lit.RegisterModel[NotificationChannel](driver)+ lit.RegisterModel[NotificationRule](driver)+ lit.RegisterModel[NotificationHistory](driver)+ lit.RegisterModel[NotificationRuleWithChannel](driver)for _, register := range ExtensionModelRegistrations {register(driver)diff --git a/backend/app/models/notification.model.go b/backend/app/models/notification.model.gonew file mode 100644index 00000000..a6114b99--- /dev/null+++ b/backend/app/models/notification.model.go@@ -0,0 +1,68 @@+package models++import (+ "encoding/json"+ "time"++ "github.com/google/uuid"+)++type NotificationChannel struct {+ Id int `json:"id" lit:"id"`+ ProjectId uuid.UUID `json:"projectId" lit:"project_id"`+ Name string `json:"name" lit:"name"`+ ChannelType string `json:"channelType" lit:"channel_type"`+ Config json.RawMessage `json:"config" lit:"config"`+ Enabled bool `json:"enabled" lit:"enabled"`+ CreatedBy *int `json:"createdBy" lit:"created_by"`+ CreatedAt time.Time `json:"createdAt" lit:"created_at"`+ UpdatedAt time.Time `json:"updatedAt" lit:"updated_at"`+}++type NotificationRule struct {+ Id int `json:"id" lit:"id"`+ ProjectId uuid.UUID `json:"projectId" lit:"project_id"`+ ChannelId int `json:"channelId" lit:"channel_id"`+ Name string `json:"name" lit:"name"`+ RuleType string `json:"ruleType" lit:"rule_type"`+ Config json.RawMessage `json:"config" lit:"config"`+ Enabled bool `json:"enabled" lit:"enabled"`+ CooldownMinutes int `json:"cooldownMinutes" lit:"cooldown_minutes"`+ SnoozedUntil *time.Time `json:"snoozedUntil" lit:"snoozed_until"`+ CreatedBy *int `json:"createdBy" lit:"created_by"`+ CreatedAt time.Time `json:"createdAt" lit:"created_at"`+ UpdatedAt time.Time `json:"updatedAt" lit:"updated_at"`+}++type NotificationHistory struct {+ Id int `json:"id" lit:"id"`+ ProjectId uuid.UUID `json:"projectId" lit:"project_id"`+ RuleId *int `json:"ruleId" lit:"rule_id"`+ ChannelId *int `json:"channelId" lit:"channel_id"`+ RuleType string `json:"ruleType" lit:"rule_type"`+ RuleName string `json:"ruleName" lit:"rule_name"`+ ChannelName string `json:"channelName" lit:"channel_name"`+ Severity string `json:"severity" lit:"severity"`+ Subject string `json:"subject" lit:"subject"`+ Body string `json:"body" lit:"body"`+ Status string `json:"status" lit:"status"`+ ErrorMessage *string `json:"errorMessage" lit:"error_message"`+ CreatedAt time.Time `json:"createdAt" lit:"created_at"`+}++type NotificationRuleWithChannel struct {+ Id int `json:"id" lit:"id"`+ ProjectId uuid.UUID `json:"projectId" lit:"project_id"`+ ChannelId int `json:"channelId" lit:"channel_id"`+ Name string `json:"name" lit:"name"`+ RuleType string `json:"ruleType" lit:"rule_type"`+ Config json.RawMessage `json:"config" lit:"config"`+ Enabled bool `json:"enabled" lit:"enabled"`+ CooldownMinutes int `json:"cooldownMinutes" lit:"cooldown_minutes"`+ SnoozedUntil *time.Time `json:"snoozedUntil" lit:"snoozed_until"`+ CreatedBy *int `json:"createdBy" lit:"created_by"`+ CreatedAt time.Time `json:"createdAt" lit:"created_at"`+ UpdatedAt time.Time `json:"updatedAt" lit:"updated_at"`+ ChannelName string `json:"channelName" lit:"channel_name"`+ ChannelType string `json:"channelType" lit:"channel_type"`+}diff --git a/backend/app/notifications/adapter_email.go b/backend/app/notifications/adapter_email.gonew file mode 100644index 00000000..287c61d4--- /dev/null+++ b/backend/app/notifications/adapter_email.go@@ -0,0 +1,66 @@+package notifications++import (+ "context"+ "fmt"+ "net/smtp"+ "strings"++ "github.com/tracewayapp/traceway/backend/app/config"+ "github.com/tracewayapp/traceway/backend/app/services"+)++type EmailAdapter struct {+ Recipients []string `json:"recipients"`+}++func (a *EmailAdapter) Type() string { return "email" }++func (a *EmailAdapter) Validate() error {+ if len(a.Recipients) == 0 {+ return fmt.Errorf("at least one recipient is required")+ }+ if len(a.Recipients) > 10 {+ return fmt.Errorf("maximum 10 recipients allowed")+ }+ for _, r := range a.Recipients {+ if !strings.Contains(r, "@") {+ return fmt.Errorf("invalid email address: %s", r)+ }+ }+ return nil+}++func (a *EmailAdapter) Send(ctx context.Context, msg Message) error {+ emailSvc := services.EmailService+ if emailSvc == nil {+ return fmt.Errorf("email service not initialized")+ }++ prefix := ""+ switch msg.Severity {+ case SeverityCritical:+ prefix = "[CRITICAL] "+ case SeverityWarning:+ prefix = "[WARNING] "+ case SeverityInfo:+ prefix = "[INFO] "+ }++ subject := prefix + msg.Subject++ if !emailSvc.IsEnabled() {+ config.Logf("[EMAIL LOG] To: %s\nSubject: %s\nBody:\n%s", strings.Join(a.Recipients, ", "), subject, msg.Body)+ return nil+ }++ cfg := config.Config+ from := cfg.SMTPFrom+ auth := smtp.PlainAuth("", cfg.SMTPUsername, cfg.SMTPPassword, cfg.SMTPHost)+ addr := fmt.Sprintf("%s:%s", cfg.SMTPHost, cfg.SMTPPort)++ emailMsg := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s",+ from, strings.Join(a.Recipients, ", "), subject, msg.Body)++ return smtp.SendMail(addr, auth, from, a.Recipients, []byte(emailMsg))+}diff --git a/backend/app/notifications/adapter_github.go b/backend/app/notifications/adapter_github.gonew file mode 100644index 00000000..db5fdc03--- /dev/null+++ b/backend/app/notifications/adapter_github.go@@ -0,0 +1,73 @@+package notifications++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "time"+)++type GitHubAdapter struct {+ Token string `json:"token"`+ Owner string `json:"owner"`+ Repo string `json:"repo"`+ Labels []string `json:"labels,omitempty"`+}++func (a *GitHubAdapter) Type() string { return "github" }++func (a *GitHubAdapter) Validate() error {+ if a.Token == "" {+ return fmt.Errorf("GitHub token is required")+ }+ if a.Owner == "" {+ return fmt.Errorf("GitHub owner is required")+ }+ if a.Repo == "" {+ return fmt.Errorf("GitHub repo is required")+ }+ return nil+}++func (a *GitHubAdapter) Send(ctx context.Context, msg Message) error {+ url := fmt.Sprintf("https://api.github.com/repos/%s/%s/issues", a.Owner, a.Repo)++ payload := map[string]interface{}{+ "title": msg.Subject,+ "body": msg.Body,+ }+ if len(a.Labels) > 0 {+ payload["labels"] = a.Labels+ }++ body, err := json.Marshal(payload)+ if err != nil {+ return fmt.Errorf("failed to marshal GitHub payload: %w", err)+ }++ req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))+ if err != nil {+ return fmt.Errorf("failed to create GitHub request: %w", err)+ }++ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Authorization", "Bearer "+a.Token)+ req.Header.Set("Accept", "application/vnd.github+json")++ client := &http.Client{Timeout: 10 * time.Second}+ resp, err := client.Do(req)+ if err != nil {+ return fmt.Errorf("GitHub request failed: %w", err)+ }+ defer resp.Body.Close()+ io.Copy(io.Discard, resp.Body)++ if resp.StatusCode != 201 {+ return fmt.Errorf("GitHub returned status %d", resp.StatusCode)+ }++ return nil+}diff --git a/backend/app/notifications/adapter_slack.go b/backend/app/notifications/adapter_slack.gonew file mode 100644index 00000000..de9b755a--- /dev/null+++ b/backend/app/notifications/adapter_slack.go@@ -0,0 +1,83 @@+package notifications++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "time"+)++type SlackAdapter struct {+ WebhookURL string `json:"webhookUrl"`+ Channel string `json:"channel,omitempty"`+ Username string `json:"username,omitempty"`+}++func (a *SlackAdapter) Type() string { return "slack" }++func (a *SlackAdapter) Validate() error {+ if a.WebhookURL == "" {+ return fmt.Errorf("Slack webhook URL is required")+ }+ return nil+}++func (a *SlackAdapter) Send(ctx context.Context, msg Message) error {+ color := "#2196F3"+ switch msg.Severity {+ case SeverityWarning:+ color = "#FF9800"+ case SeverityCritical:+ color = "#F44336"+ }++ username := a.Username+ if username == "" {+ username = "Traceway"+ }++ payload := map[string]interface{}{+ "username": username,+ "attachments": []map[string]interface{}{+ {+ "color": color,+ "title": msg.Subject,+ "text": msg.Body,+ "footer": "Traceway Alerts",+ "ts": time.Now().Unix(),+ },+ },+ }++ if a.Channel != "" {+ payload["channel"] = a.Channel+ }++ body, err := json.Marshal(payload)+ if err != nil {+ return fmt.Errorf("failed to marshal Slack payload: %w", err)+ }++ req, err := http.NewRequestWithContext(ctx, "POST", a.WebhookURL, bytes.NewReader(body))+ if err != nil {+ return fmt.Errorf("failed to create Slack request: %w", err)+ }+ req.Header.Set("Content-Type", "application/json")++ client := &http.Client{Timeout: 10 * time.Second}+ resp, err := client.Do(req)+ if err != nil {+ return fmt.Errorf("Slack request failed: %w", err)+ }+ defer resp.Body.Close()+ io.Copy(io.Discard, resp.Body)++ if resp.StatusCode != 200 {+ return fmt.Errorf("Slack returned status %d", resp.StatusCode)+ }++ return nil+}diff --git a/backend/app/notifications/adapter_webhook.go b/backend/app/notifications/adapter_webhook.gonew file mode 100644index 00000000..c691fa74--- /dev/null+++ b/backend/app/notifications/adapter_webhook.go@@ -0,0 +1,87 @@+package notifications++import (+ "bytes"+ "context"+ "crypto/hmac"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "time"+)++type WebhookAdapter struct {+ URL string `json:"url"`+ Method string `json:"method,omitempty"`+ Headers map[string]string `json:"headers,omitempty"`+ Secret string `json:"secret,omitempty"`+}++func (a *WebhookAdapter) Type() string { return "webhook" }++func (a *WebhookAdapter) Validate() error {+ if a.URL == "" {+ return fmt.Errorf("webhook URL is required")+ }+ if a.Method == "" {+ a.Method = "POST"+ }+ return nil+}++func (a *WebhookAdapter) Send(ctx context.Context, msg Message) error {+ payload := map[string]string{+ "subject": msg.Subject,+ "body": msg.Body,+ "severity": string(msg.Severity),+ "ruleType": msg.RuleType,+ "ruleName": msg.RuleName,+ "url": msg.URL,+ "timestamp": time.Now().UTC().Format(time.RFC3339),+ }++ body, err := json.Marshal(payload)+ if err != nil {+ return fmt.Errorf("failed to marshal webhook payload: %w", err)+ }++ method := a.Method+ if method == "" {+ method = "POST"+ }++ req, err := http.NewRequestWithContext(ctx, method, a.URL, bytes.NewReader(body))+ if err != nil {+ return fmt.Errorf("failed to create webhook request: %w", err)+ }++ req.Header.Set("Content-Type", "application/json")++ for k, v := range a.Headers {+ req.Header.Set(k, v)+ }++ if a.Secret != "" {+ mac := hmac.New(sha256.New, []byte(a.Secret))+ mac.Write(body)+ sig := hex.EncodeToString(mac.Sum(nil))+ req.Header.Set("X-Traceway-Signature", "sha256="+sig)+ }++ client := &http.Client{Timeout: 10 * time.Second}+ resp, err := client.Do(req)+ if err != nil {+ return fmt.Errorf("webhook request failed: %w", err)+ }+ defer resp.Body.Close()+ io.Copy(io.Discard, resp.Body)++ if resp.StatusCode >= 400 {+ return fmt.Errorf("webhook returned status %d", resp.StatusCode)+ }++ return nil+}diff --git a/backend/app/notifications/adapters.go b/backend/app/notifications/adapters.gonew file mode 100644index 00000000..77ac0986--- /dev/null+++ b/backend/app/notifications/adapters.go@@ -0,0 +1,63 @@+package notifications++import (+ "context"+ "encoding/json"+ "fmt"+)++type Severity string++const (+ SeverityInfo Severity = "info"+ SeverityWarning Severity = "warning"+ SeverityCritical Severity = "critical"+)++type Message struct {+ Subject string+ Body string+ HTMLBody string+ Severity Severity+ RuleType string+ RuleName string+ URL string+ Endpoint string+}++type Adapter interface {+ Type() string+ Send(ctx context.Context, msg Message) error+ Validate() error+}++func NewAdapter(channelType string, configJSON json.RawMessage) (Adapter, error) {+ switch channelType {+ case "email":+ var cfg EmailAdapter+ if err := json.Unmarshal(configJSON, &cfg); err != nil {+ return nil, fmt.Errorf("invalid email config: %w", err)+ }+ return &cfg, nil+ case "webhook":+ var cfg WebhookAdapter+ if err := json.Unmarshal(configJSON, &cfg); err != nil {+ return nil, fmt.Errorf("invalid webhook config: %w", err)+ }+ return &cfg, nil+ case "slack":+ var cfg SlackAdapter+ if err := json.Unmarshal(configJSON, &cfg); err != nil {+ return nil, fmt.Errorf("invalid slack config: %w", err)+ }+ return &cfg, nil+ case "github":+ var cfg GitHubAdapter+ if err := json.Unmarshal(configJSON, &cfg); err != nil {+ return nil, fmt.Errorf("invalid github config: %w", err)+ }+ return &cfg, nil+ default:+ return nil, fmt.Errorf("unknown channel type: %s", channelType)+ }+}diff --git a/backend/app/notifications/cooldown.go b/backend/app/notifications/cooldown.gonew file mode 100644index 00000000..5686c0bf--- /dev/null+++ b/backend/app/notifications/cooldown.go@@ -0,0 +1,76 @@+package notifications++import (+ "context"+ "sync"+ "time"+)++type cooldownTracker struct {+ mu sync.RWMutex+ fired map[int]time.Time+}++var cooldowns = &cooldownTracker{fired: make(map[int]time.Time)}++func (m *cooldownTracker) canFire(ruleId int, cooldownMinutes int) bool {+ m.mu.RLock()+ defer m.mu.RUnlock()+ last, ok := m.fired[ruleId]+ if !ok {+ return true+ }+ return time.Since(last) > time.Duration(cooldownMinutes)*time.Minute+}++func (m *cooldownTracker) recordFire(ruleId int) {+ m.mu.Lock()+ defer m.mu.Unlock()+ m.fired[ruleId] = time.Now()+}++type dedupTracker struct {+ mu sync.RWMutex+ seen map[string]time.Time+}++var dedup = &dedupTracker{seen: make(map[string]time.Time)}++func (m *dedupTracker) isDuplicate(key string, cooldown time.Duration) bool {+ m.mu.RLock()+ defer m.mu.RUnlock()+ last, ok := m.seen[key]+ return ok && time.Since(last) < cooldown+}++func (m *dedupTracker) record(key string) {+ m.mu.Lock()+ defer m.mu.Unlock()+ m.seen[key] = time.Now()+}++func (m *dedupTracker) purgeExpired(maxAge time.Duration) {+ m.mu.Lock()+ defer m.mu.Unlock()+ now := time.Now()+ for k, t := range m.seen {+ if now.Sub(t) > maxAge {+ delete(m.seen, k)+ }+ }+}++func startDedupPurger(ctx context.Context) {+ go func() {+ ticker := time.NewTicker(10 * time.Minute)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ dedup.purgeExpired(24 * time.Hour)+ }+ }+ }()+}diff --git a/backend/app/notifications/dispatch.go b/backend/app/notifications/dispatch.gonew file mode 100644index 00000000..8e7298cf--- /dev/null+++ b/backend/app/notifications/dispatch.go@@ -0,0 +1,104 @@+package notifications++import (+ "context"+ "database/sql"+ "fmt"+ "time"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories"+ traceway "go.tracewayapp.com"+)++func dispatch(rule *models.NotificationRuleWithChannel, msg Message) {+ channel, dbErr := db.ExecuteTransaction(func(tx *sql.Tx) (*models.NotificationChannel, error) {+ return repositories.NotificationChannelRepository.FindById(tx, rule.ChannelId)+ })+ if dbErr != nil || channel == nil {+ recordHistory(rule, msg, "failed", "failed to load channel")+ recordFiredNotification(rule, msg, "failed", "failed to load channel")+ return+ }++ adapter, err := NewAdapter(channel.ChannelType, channel.Config)+ if err != nil {+ recordHistory(rule, msg, "failed", err.Error())+ recordFiredNotification(rule, msg, "failed", err.Error())+ return+ }++ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()++ msg.RuleType = rule.RuleType+ msg.RuleName = rule.Name++ err = adapter.Send(ctx, msg)+ if err != nil {+ recordHistory(rule, msg, "failed", err.Error())+ recordFiredNotification(rule, msg, "failed", err.Error())+ traceway.CaptureException(fmt.Errorf("notification dispatch failed (rule=%d, channel=%s): %w", rule.Id, rule.ChannelName, err))+ return+ }++ recordHistory(rule, msg, "sent", "")+ recordFiredNotification(rule, msg, "sent", "")+ cooldowns.recordFire(rule.Id)+}++func recordFiredNotification(rule *models.NotificationRuleWithChannel, msg Message, status string, errorMsg string) {+ go func() {+ err := repositories.FiredNotificationRepository.Insert(context.Background(), repositories.FiredNotification{+ ProjectId: rule.ProjectId,+ RuleId: rule.Id,+ RuleType: rule.RuleType,+ RuleName: rule.Name,+ ChannelType: rule.ChannelType,+ ChannelName: rule.ChannelName,+ Severity: string(msg.Severity),+ Subject: msg.Subject,+ Body: msg.Body,+ Status: status,+ ErrorMsg: errorMsg,+ Endpoint: msg.Endpoint,+ FiredAt: time.Now().UTC(),+ })+ if err != nil {+ traceway.CaptureException(fmt.Errorf("failed to record fired notification to ClickHouse: %w", err))+ }+ }()+}++func recordHistory(rule *models.NotificationRuleWithChannel, msg Message, status string, errorMsg string) {+ var errMsgPtr *string+ if errorMsg != "" {+ errMsgPtr = &errorMsg+ }++ ruleId := rule.Id+ channelId := rule.ChannelId++ history := &models.NotificationHistory{+ ProjectId: rule.ProjectId,+ RuleId: &ruleId,+ ChannelId: &channelId,+ RuleType: rule.RuleType,+ RuleName: rule.Name,+ ChannelName: rule.ChannelName,+ Severity: string(msg.Severity),+ Subject: msg.Subject,+ Body: msg.Body,+ Status: status,+ ErrorMessage: errMsgPtr,+ CreatedAt: time.Now().UTC(),+ }++ _, dbErr := db.ExecuteTransaction(func(tx *sql.Tx) (int, error) {+ return repositories.NotificationHistoryRepository.Create(tx, history)+ })+ if dbErr != nil {+ traceway.CaptureException(fmt.Errorf("failed to record notification history: %w", dbErr))+ }+}diff --git a/backend/app/notifications/evaluator.go b/backend/app/notifications/evaluator.gonew file mode 100644index 00000000..f64bd403--- /dev/null+++ b/backend/app/notifications/evaluator.go@@ -0,0 +1,84 @@+package notifications++import (+ "context"+ "database/sql"+ "fmt"+ "time"++ "github.com/tracewayapp/traceway/backend/app/config"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories"+ traceway "go.tracewayapp.com"+)++func StartEvaluator(ctx context.Context) {+ config.Logln("Starting notification evaluator")+ startDedupPurger(ctx)+ registerReportHook()+ go startPolledLoop(ctx)+}++func startPolledLoop(ctx context.Context) {+ ticker := time.NewTicker(60 * time.Second)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ evaluatePolledRules(ctx)+ }+ }+}++func evaluatePolledRules(ctx context.Context) {+ rules, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.NotificationRuleWithChannel, error) {+ return repositories.NotificationRuleRepository.FindEnabledPolledRules(tx)+ })+ if err != nil {+ traceway.CaptureException(fmt.Errorf("failed to load polled notification rules: %w", err))+ return+ }++ for _, rule := range rules {+ if rule.SnoozedUntil != nil && rule.SnoozedUntil.After(time.Now()) {+ continue+ }++ if !cooldowns.canFire(rule.Id, rule.CooldownMinutes) {+ continue+ }++ evaluator, ok := polledEvaluators[rule.RuleType]+ if !ok {+ continue+ }++ nr := &models.NotificationRule{+ Id: rule.Id,+ ProjectId: rule.ProjectId,+ ChannelId: rule.ChannelId,+ Name: rule.Name,+ RuleType: rule.RuleType,+ Config: rule.Config,+ Enabled: rule.Enabled,+ CooldownMinutes: rule.CooldownMinutes,+ SnoozedUntil: rule.SnoozedUntil,+ CreatedBy: rule.CreatedBy,+ CreatedAt: rule.CreatedAt,+ UpdatedAt: rule.UpdatedAt,+ }+ result, err := evaluator(ctx, nr, rule.ProjectId)+ if err != nil {+ traceway.CaptureException(fmt.Errorf("notification evaluator error (rule=%d, type=%s): %w", rule.Id, rule.RuleType, err))+ continue+ }++ if result != nil && result.Fired {+ dispatch(rule, result.Message)+ }+ }+}diff --git a/backend/app/notifications/evaluator_event.go b/backend/app/notifications/evaluator_event.gonew file mode 100644index 00000000..2abd81ce--- /dev/null+++ b/backend/app/notifications/evaluator_event.go@@ -0,0 +1,154 @@+package notifications++import (+ "context"+ "database/sql"+ "encoding/json"+ "fmt"+ "strings"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/chdb"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/hooks"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories"+ traceway "go.tracewayapp.com"+)++func registerReportHook() {+ hooks.RegisterReportHook(func(event hooks.ReportEvent) {+ if len(event.ExceptionHashes) == 0 {+ return+ }+ go evaluateEventRules(event)+ })+}++func evaluateEventRules(event hooks.ReportEvent) {+ rules, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.NotificationRuleWithChannel, error) {+ return repositories.NotificationRuleRepository.FindEnabledEventRules(tx, event.ProjectId)+ })+ if err != nil {+ traceway.CaptureException(fmt.Errorf("failed to load event notification rules: %w", err))+ return+ }++ ctx := context.Background()++ for _, rule := range rules {+ if rule.SnoozedUntil != nil && rule.SnoozedUntil.After(time.Now()) {+ continue+ }++ switch rule.RuleType {+ case "new_error":+ evaluateNewError(ctx, rule, event)+ case "error_regression":+ evaluateErrorRegression(ctx, rule, event)+ }+ }+}++type newErrorConfig struct {+ IgnorePatterns []string `json:"ignorePatterns"`+}++func evaluateNewError(ctx context.Context, rule *models.NotificationRuleWithChannel, event hooks.ReportEvent) {+ var cfg newErrorConfig+ json.Unmarshal(rule.Config, &cfg)++ for _, hash := range event.ExceptionHashes {+ dedupKey := fmt.Sprintf("%d:%s", rule.Id, hash)+ if dedup.isDuplicate(dedupKey, time.Duration(rule.CooldownMinutes)*time.Minute) {+ continue+ }++ var count uint64+ err := chdb.Conn.QueryRow(ctx,+ "SELECT count() FROM exception_stack_traces WHERE project_id = ? AND exception_hash = ?",+ event.ProjectId, hash).Scan(&count)+ if err != nil {+ traceway.CaptureException(fmt.Errorf("new_error check failed: %w", err))+ continue+ }++ // count > 1 means this hash already existed before this batch+ if count > 1 {+ continue+ }++ errorType := getErrorTypeForHash(ctx, event.ProjectId, hash)++ if shouldIgnore(errorType, cfg.IgnorePatterns) {+ continue+ }++ dedup.record(dedupKey)+ msg := buildNewErrorMessage(errorType, hash, "")+ dispatch(rule, msg)+ }+}++func evaluateErrorRegression(ctx context.Context, rule *models.NotificationRuleWithChannel, event hooks.ReportEvent) {+ for _, hash := range event.ExceptionHashes {+ dedupKey := fmt.Sprintf("%d:%s", rule.Id, hash)+ if dedup.isDuplicate(dedupKey, time.Duration(rule.CooldownMinutes)*time.Minute) {+ continue+ }++ // Check if this hash was previously archived (resolved)+ var count uint64+ err := chdb.Conn.QueryRow(ctx,+ "SELECT count() FROM archived_exceptions FINAL WHERE project_id = ? AND exception_hash = ?",+ event.ProjectId, hash).Scan(&count)+ if err != nil {+ traceway.CaptureException(fmt.Errorf("error_regression check failed: %w", err))+ continue+ }++ if count == 0 {+ continue+ }++ errorType := getErrorTypeForHash(ctx, event.ProjectId, hash)+ dedup.record(dedupKey)+ msg := buildErrorRegressionMessage(errorType, hash, "")+ dispatch(rule, msg)+ }+}++func getErrorTypeForHash(ctx context.Context, projectId uuid.UUID, hash string) string {+ var stackTrace string+ err := chdb.Conn.QueryRow(ctx,+ "SELECT stack_trace FROM exception_stack_traces WHERE project_id = ? AND exception_hash = ? ORDER BY recorded_at DESC LIMIT 1",+ projectId, hash).Scan(&stackTrace)+ if err != nil || stackTrace == "" {+ return "Unknown Error"+ }+ lines := strings.SplitN(stackTrace, "\n", 2)+ if len(lines) > 0 {+ line := strings.TrimSpace(lines[0])+ if idx := strings.Index(line, ":"); idx > 0 {+ return line[:idx]+ }+ return line+ }+ return "Unknown Error"+}++func shouldIgnore(errorType string, patterns []string) bool {+ lower := strings.ToLower(errorType)+ for _, pattern := range patterns {+ pattern = strings.ToLower(strings.TrimSpace(pattern))+ if pattern == "" {+ continue+ }+ pattern = strings.ReplaceAll(pattern, "*", "")+ if strings.Contains(lower, pattern) {+ return true+ }+ }+ return false+}diff --git a/backend/app/notifications/evaluator_polled.go b/backend/app/notifications/evaluator_polled.gonew file mode 100644index 00000000..3c4bf060--- /dev/null+++ b/backend/app/notifications/evaluator_polled.go@@ -0,0 +1,684 @@+package notifications++import (+ "context"+ "encoding/json"+ "fmt"+ "sync"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/chdb"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories"+)++type EvalResult struct {+ Fired bool+ Message Message+}++type RuleEvaluator func(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error)++var polledEvaluators = map[string]RuleEvaluator{+ "error_rate_threshold": evaluateErrorRateThreshold,+ "endpoint_p95_threshold": evaluateEndpointP95Threshold,+ "endpoint_p99_threshold": evaluateEndpointP99Threshold,+ "apdex_drop": evaluateApdexDrop,+ "metric_threshold": evaluateMetricThreshold,+ "no_data": evaluateNoData,+ "error_count_threshold": evaluateErrorCountThreshold,+ "task_duration_threshold": evaluateTaskDurationThreshold,+ "throughput_drop": evaluateThroughputDrop,+ "endpoint_error_rate": evaluateEndpointErrorRate,+ "impact_score_critical": evaluateImpactScoreCritical,+ "impact_score_high": evaluateImpactScoreHigh,+ "impact_score_medium": evaluateImpactScoreMedium,+}++// --- Error Rate Threshold ---++type errorRateConfig struct {+ ThresholdPercent float64 `json:"thresholdPercent"`+ LookbackMinutes int `json:"lookbackMinutes"`+ MinRequests int `json:"minRequests"`+}++func evaluateErrorRateThreshold(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg errorRateConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid error_rate_threshold config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 5+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ var total, errors uint64+ err := chdb.Conn.QueryRow(ctx,+ "SELECT count() as total, countIf(status_code >= 500) as errors FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?",+ projectId, from, now).Scan(&total, &errors)+ if err != nil {+ return nil, err+ }++ if total < uint64(cfg.MinRequests) {+ return &EvalResult{Fired: false}, nil+ }++ rate := float64(errors) / float64(total) * 100+ if rate < cfg.ThresholdPercent {+ return &EvalResult{Fired: false}, nil+ }++ msg := buildErrorRateMessage(rate, cfg.ThresholdPercent, cfg.LookbackMinutes, "")+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Endpoint P95 Threshold ---++type endpointLatencyConfig struct {+ Endpoint string `json:"endpoint"`+ ThresholdMs float64 `json:"thresholdMs"`+ LookbackMinutes int `json:"lookbackMinutes"`+}++func evaluateEndpointP95Threshold(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg endpointLatencyConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid endpoint_p95_threshold config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 5+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ // duration is stored in nanoseconds, convert to milliseconds+ query := "SELECT quantile(0.95)(duration / 1000000) as p95 FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?"+ args := []interface{}{projectId, from, now}+ if cfg.Endpoint != "" && cfg.Endpoint != "*" {+ query += " AND endpoint = ?"+ args = append(args, cfg.Endpoint)+ }++ var p95 float64+ err := chdb.Conn.QueryRow(ctx, query, args...).Scan(&p95)+ if err != nil {+ return nil, err+ }++ if p95 < cfg.ThresholdMs {+ return &EvalResult{Fired: false}, nil+ }++ endpoint := cfg.Endpoint+ if endpoint == "" || endpoint == "*" {+ endpoint = "all endpoints"+ }+ msg := buildEndpointLatencyMessage("P95", p95, cfg.ThresholdMs, endpoint, "")+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Endpoint P99 Threshold ---++func evaluateEndpointP99Threshold(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg endpointLatencyConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid endpoint_p99_threshold config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 5+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ query := "SELECT quantile(0.99)(duration / 1000000) as p99 FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?"+ args := []interface{}{projectId, from, now}+ if cfg.Endpoint != "" && cfg.Endpoint != "*" {+ query += " AND endpoint = ?"+ args = append(args, cfg.Endpoint)+ }++ var p99 float64+ err := chdb.Conn.QueryRow(ctx, query, args...).Scan(&p99)+ if err != nil {+ return nil, err+ }++ if p99 < cfg.ThresholdMs {+ return &EvalResult{Fired: false}, nil+ }++ endpoint := cfg.Endpoint+ if endpoint == "" || endpoint == "*" {+ endpoint = "all endpoints"+ }+ msg := buildEndpointLatencyMessage("P99", p99, cfg.ThresholdMs, endpoint, "")+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Apdex Drop ---++type apdexConfig struct {+ ThresholdApdex float64 `json:"thresholdApdex"`+ LookbackMinutes int `json:"lookbackMinutes"`+ MinRequests int `json:"minRequests"`+}++func evaluateApdexDrop(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg apdexConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid apdex_drop config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 15+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ // Apdex thresholds: Good <= 750ms (750000000ns), Tolerable <= 1500ms (1500000000ns)+ var total, satisfied, tolerating uint64+ err := chdb.Conn.QueryRow(ctx,+ `SELECT count() as total,+ countIf(duration <= 750000000 AND status_code < 500) as satisfied,+ countIf(duration > 750000000 AND duration <= 1500000000 AND status_code < 500) as tolerating+ FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?`,+ projectId, from, now).Scan(&total, &satisfied, &tolerating)+ if err != nil {+ return nil, err+ }++ if total < uint64(cfg.MinRequests) {+ return &EvalResult{Fired: false}, nil+ }++ apdex := (float64(satisfied) + float64(tolerating)/2.0) / float64(total)+ if apdex >= cfg.ThresholdApdex {+ return &EvalResult{Fired: false}, nil+ }++ msg := buildApdexDropMessage(apdex, cfg.ThresholdApdex, "")+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Metric Threshold ---++type metricThresholdConfig struct {+ MetricName string `json:"metricName"`+ Operator string `json:"operator"`+ ThresholdValue float64 `json:"thresholdValue"`+ Aggregation string `json:"aggregation"`+ LookbackMinutes int `json:"lookbackMinutes"`+}++func evaluateMetricThreshold(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg metricThresholdConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid metric_threshold config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 5+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ aggFunc := "avg"+ switch cfg.Aggregation {+ case "max":+ aggFunc = "max"+ case "min":+ aggFunc = "min"+ case "sum":+ aggFunc = "sum"+ case "p95":+ aggFunc = "quantile(0.95)"+ case "p99":+ aggFunc = "quantile(0.99)"+ }++ query := fmt.Sprintf("SELECT %s(value) FROM metric_points WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ?", aggFunc)+ args := []interface{}{projectId, cfg.MetricName, from, now}++ var value float64+ err := chdb.Conn.QueryRow(ctx, query, args...).Scan(&value)+ if err != nil {+ return nil, err+ }++ fired := false+ switch cfg.Operator {+ case "gt":+ fired = value > cfg.ThresholdValue+ case "gte":+ fired = value >= cfg.ThresholdValue+ case "lt":+ fired = value < cfg.ThresholdValue+ case "lte":+ fired = value <= cfg.ThresholdValue+ case "eq":+ fired = value == cfg.ThresholdValue+ }++ if !fired {+ return &EvalResult{Fired: false}, nil+ }++ msg := buildMetricThresholdMessage(cfg.MetricName, value, cfg.Operator, cfg.ThresholdValue, "")+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- No Data ---++type noDataConfig struct {+ DataType string `json:"dataType"`+ SilenceMinutes int `json:"silenceMinutes"`+}++func evaluateNoData(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg noDataConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid no_data config: %w", err)+ }+ if cfg.SilenceMinutes <= 0 {+ cfg.SilenceMinutes = 10+ }++ threshold := time.Now().UTC().Add(-time.Duration(cfg.SilenceMinutes) * time.Minute)++ if cfg.DataType == "any" {+ tables := []string{"endpoints", "exception_stack_traces", "metric_points", "tasks"}+ for _, t := range tables {+ var maxTs time.Time+ err := chdb.Conn.QueryRow(ctx,+ fmt.Sprintf("SELECT max(recorded_at) FROM %s WHERE project_id = ?", t),+ projectId).Scan(&maxTs)+ if err == nil && maxTs.After(threshold) {+ return &EvalResult{Fired: false}, nil+ }+ }+ msg := buildNoDataMessage("any", cfg.SilenceMinutes, "")+ return &EvalResult{Fired: true, Message: msg}, nil+ }++ table := ""+ switch cfg.DataType {+ case "endpoints":+ table = "endpoints"+ case "exceptions":+ table = "exception_stack_traces"+ case "metrics":+ table = "metric_points"+ case "tasks":+ table = "tasks"+ default:+ return nil, fmt.Errorf("unknown data type: %s", cfg.DataType)+ }++ var maxTs time.Time+ err := chdb.Conn.QueryRow(ctx,+ fmt.Sprintf("SELECT max(recorded_at) FROM %s WHERE project_id = ?", table),+ projectId).Scan(&maxTs)+ if err != nil {+ return nil, err+ }++ if maxTs.After(threshold) {+ return &EvalResult{Fired: false}, nil+ }++ msg := buildNoDataMessage(cfg.DataType, cfg.SilenceMinutes, "")+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Error Count Threshold ---++type errorCountConfig struct {+ ThresholdCount int64 `json:"thresholdCount"`+ LookbackMinutes int `json:"lookbackMinutes"`+}++func evaluateErrorCountThreshold(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg errorCountConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid error_count_threshold config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 60+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ var count uint64+ err := chdb.Conn.QueryRow(ctx,+ "SELECT count() FROM exception_stack_traces WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? AND is_message = 0",+ projectId, from, now).Scan(&count)+ if err != nil {+ return nil, err+ }++ if int64(count) < cfg.ThresholdCount {+ return &EvalResult{Fired: false}, nil+ }++ msg := buildErrorCountMessage(int64(count), cfg.ThresholdCount, cfg.LookbackMinutes, "")+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Task Duration Threshold ---++type taskDurationConfig struct {+ TaskName string `json:"taskName"`+ ThresholdMs float64 `json:"thresholdMs"`+ LookbackMinutes int `json:"lookbackMinutes"`+}++func evaluateTaskDurationThreshold(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg taskDurationConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid task_duration_threshold config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 30+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ // duration is stored in nanoseconds, convert to milliseconds+ query := "SELECT quantile(0.95)(duration / 1000000) as p95 FROM tasks WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?"+ args := []interface{}{projectId, from, now}+ if cfg.TaskName != "" && cfg.TaskName != "*" {+ query += " AND task_name = ?"+ args = append(args, cfg.TaskName)+ }++ var p95 float64+ err := chdb.Conn.QueryRow(ctx, query, args...).Scan(&p95)+ if err != nil {+ return nil, err+ }++ if p95 < cfg.ThresholdMs {+ return &EvalResult{Fired: false}, nil+ }++ taskName := cfg.TaskName+ if taskName == "" || taskName == "*" {+ taskName = "all tasks"+ }+ msg := buildTaskDurationMessage(taskName, p95, cfg.ThresholdMs, "")+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Throughput Drop ---++type throughputDropConfig struct {+ DropPercent float64 `json:"dropPercent"`+ LookbackMinutes int `json:"lookbackMinutes"`+ BaselineWindowMinutes int `json:"baselineWindowMinutes"`+}++func evaluateThroughputDrop(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg throughputDropConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid throughput_drop config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 15+ }+ if cfg.BaselineWindowMinutes <= 0 {+ cfg.BaselineWindowMinutes = 60+ }++ now := time.Now().UTC()+ lookbackFrom := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)+ baselineFrom := lookbackFrom.Add(-time.Duration(cfg.BaselineWindowMinutes) * time.Minute)++ var currentCount uint64+ err := chdb.Conn.QueryRow(ctx,+ "SELECT count() FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?",+ projectId, lookbackFrom, now).Scan(¤tCount)+ if err != nil {+ return nil, err+ }++ var baselineCount uint64+ err = chdb.Conn.QueryRow(ctx,+ "SELECT count() FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?",+ projectId, baselineFrom, lookbackFrom).Scan(&baselineCount)+ if err != nil {+ return nil, err+ }++ if baselineCount == 0 {+ return &EvalResult{Fired: false}, nil+ }++ normalizedBaseline := float64(baselineCount) * float64(cfg.LookbackMinutes) / float64(cfg.BaselineWindowMinutes)+ if normalizedBaseline == 0 {+ return &EvalResult{Fired: false}, nil+ }++ dropPercent := (1 - float64(currentCount)/normalizedBaseline) * 100+ if dropPercent < cfg.DropPercent {+ return &EvalResult{Fired: false}, nil+ }++ msg := buildThroughputDropMessage(dropPercent, "")+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Endpoint Error Rate ---++type endpointErrorRateConfig struct {+ Endpoint string `json:"endpoint"`+ ThresholdPercent float64 `json:"thresholdPercent"`+ LookbackMinutes int `json:"lookbackMinutes"`+ MinRequests int `json:"minRequests"`+}++func evaluateEndpointErrorRate(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg endpointErrorRateConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid endpoint_error_rate config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 10+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ var total, errors uint64+ err := chdb.Conn.QueryRow(ctx,+ "SELECT count() as total, countIf(status_code >= 500) as errors FROM endpoints WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?",+ projectId, cfg.Endpoint, from, now).Scan(&total, &errors)+ if err != nil {+ return nil, err+ }++ if total < uint64(cfg.MinRequests) {+ return &EvalResult{Fired: false}, nil+ }++ rate := float64(errors) / float64(total) * 100+ if rate < cfg.ThresholdPercent {+ return &EvalResult{Fired: false}, nil+ }++ msg := buildEndpointErrorRateMessage(cfg.Endpoint, rate, cfg.ThresholdPercent, "")+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Impact Score ---++var (+ impactStateMu sync.RWMutex+ impactState = make(map[string]map[string]bool)+)++type impactScoreConfig struct {+ MinRequests int `json:"minRequests"`+}++type impactMessageBuilder func(endpoint string, score float64, reason string, projectName string) Message++func evaluateImpactScore(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID, threshold float64, buildMsg impactMessageBuilder) (*EvalResult, error) {+ var cfg impactScoreConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid impact_score config: %w", err)+ }+ if cfg.MinRequests <= 0 {+ cfg.MinRequests = 50+ }++ now := time.Now().UTC()+ from := now.Add(-24 * time.Hour)++ query := fmt.Sprintf(`SELECT+ endpoint, total_count, p99_duration, offset_ms,+ satisfied_count, tolerating_count, bad_count, client_error_count,+ greatest(+ if(total_count > 0,+ 1.0 - ((satisfied_count + tolerating_count * 0.5) / total_count), 0.0),+ multiIf(+ bad_count / total_count > 0.33, 0.75,+ bad_count / total_count > 0.20, 0.50,+ bad_count / total_count > 0.10, 0.25, 0.0),+ multiIf(+ toFloat64(p99_duration) - toFloat64(offset_ms) * 1000000 > 8000000000, 0.75,+ toFloat64(p99_duration) - toFloat64(offset_ms) * 1000000 > 6000000000, 0.50,+ toFloat64(p99_duration) - toFloat64(offset_ms) * 1000000 > 3000000000, 0.25, 0.0),+ if(endpoint != 'UNMATCHED' AND total_count > 10,+ multiIf(+ client_error_count / total_count > 0.50, 0.75,+ client_error_count / total_count > 0.25, 0.50, 0.0),+ 0.0),+ multiIf(+ bad_count / total_count > 0.10 AND bad_count >= 500, 0.75,+ bad_count / total_count > 0.10 AND bad_count >= 50, 0.50,+ bad_count / total_count > 0.05 AND bad_count >= 2000, 0.75,+ bad_count / total_count > 0.05 AND bad_count >= 500, 0.50,+ bad_count / total_count > 0.05 AND bad_count >= 50, 0.25,+ bad_count / total_count > 0.01 AND bad_count >= 10000, 0.75,+ bad_count / total_count > 0.01 AND bad_count >= 2000, 0.50,+ bad_count / total_count > 0.01 AND bad_count >= 500, 0.25,+ 0.0)+ ) as impact+ FROM (+ SELECT+ endpoint,+ offset_ms,+ count() as total_count,+ quantile(0.99)(duration) as p99_duration,+ countIf(duration <= (750000000 + toInt64(offset_ms) * 1000000)+ AND status_code < 500) as satisfied_count,+ countIf(duration > (750000000 + toInt64(offset_ms) * 1000000)+ AND duration <= (1500000000 + toInt64(offset_ms) * 1000000)+ AND status_code < 500) as tolerating_count,+ countIf(duration > (1500000000 + toInt64(offset_ms) * 1000000)+ OR status_code >= 500) as bad_count,+ countIf(status_code >= 400 AND status_code < 500) as client_error_count+ FROM (+ SELECT e.endpoint, e.duration, e.status_code, e.recorded_at,+ s.offset_ms as offset_ms+ FROM endpoints e+ LEFT JOIN (SELECT * FROM slow_endpoints FINAL) AS s+ ON e.endpoint = s.endpoint AND e.project_id = s.project_id+ WHERE e.project_id = ? AND e.recorded_at >= ? AND e.recorded_at <= ?+ )+ GROUP BY endpoint, offset_ms+ )+ WHERE impact >= %.2f AND total_count >= ?`, threshold)++ rows, err := chdb.Conn.Query(ctx, query, projectId, from, now, uint64(cfg.MinRequests))+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ type impactEndpoint struct {+ endpoint string+ impact float64+ totalCount uint64+ p99 float64+ offsetMs uint32+ satisfied uint64+ tolerating uint64+ bad uint64+ clientErrors uint64+ }++ currentSet := make(map[string]impactEndpoint)+ for rows.Next() {+ var ep string+ var totalCount, satisfied, tolerating, bad, clientErrors uint64+ var p99 float64+ var offsetMs uint32+ var impact float64+ if err := rows.Scan(&ep, &totalCount, &p99, &offsetMs,+ &satisfied, &tolerating, &bad, &clientErrors, &impact); err != nil {+ return nil, err+ }+ currentSet[ep] = impactEndpoint{+ endpoint: ep,+ impact: impact,+ totalCount: totalCount,+ p99: p99,+ offsetMs: offsetMs,+ satisfied: satisfied,+ tolerating: tolerating,+ bad: bad,+ clientErrors: clientErrors,+ }+ }++ stateKey := fmt.Sprintf("%d:%s", rule.Id, projectId.String())++ impactStateMu.RLock()+ prevSet := impactState[stateKey]+ impactStateMu.RUnlock()++ newSet := make(map[string]bool)+ for ep := range currentSet {+ newSet[ep] = true+ }++ impactStateMu.Lock()+ impactState[stateKey] = newSet+ impactStateMu.Unlock()++ for ep, data := range currentSet {+ if prevSet != nil && prevSet[ep] {+ continue+ }+ reason := repositories.ComputeImpactReason(+ ep, data.totalCount, data.satisfied, data.tolerating,+ data.bad, data.clientErrors, data.p99, data.offsetMs,+ )+ msg := buildMsg(ep, data.impact, reason, "")+ return &EvalResult{Fired: true, Message: msg}, nil+ }++ return &EvalResult{Fired: false}, nil+}++func evaluateImpactScoreCritical(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ return evaluateImpactScore(ctx, rule, projectId, 0.75, buildImpactScoreCriticalMessage)+}++func evaluateImpactScoreHigh(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ return evaluateImpactScore(ctx, rule, projectId, 0.50, buildImpactScoreHighMessage)+}++func evaluateImpactScoreMedium(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ return evaluateImpactScore(ctx, rule, projectId, 0.25, buildImpactScoreMediumMessage)+}diff --git a/backend/app/notifications/messages.go b/backend/app/notifications/messages.gonew file mode 100644index 00000000..720776de--- /dev/null+++ b/backend/app/notifications/messages.go@@ -0,0 +1,162 @@+package notifications++import (+ "fmt"+)++func buildErrorRateMessage(rate float64, threshold float64, window int, projectName string) Message {+ severity := SeverityWarning+ if rate >= threshold*2 {+ severity = SeverityCritical+ }+ return Message{+ Subject: fmt.Sprintf("[%s] Error rate %.1f%% exceeds %.1f%%", projectName, rate, threshold),+ Body: fmt.Sprintf("The error rate has reached %.1f%% over the last %d minutes (threshold: %.1f%%).", rate, window, threshold),+ Severity: severity,+ URL: "/issues?preset=1h",+ }+}++func buildEndpointLatencyMessage(percentile string, latencyMs float64, thresholdMs float64, endpoint string, projectName string) Message {+ return Message{+ Subject: fmt.Sprintf("[%s] %s latency %.0fms on %s", projectName, percentile, latencyMs, endpoint),+ Body: fmt.Sprintf("The %s latency for %s has reached %.0fms (threshold: %.0fms).", percentile, endpoint, latencyMs, thresholdMs),+ Severity: SeverityWarning,+ URL: "/endpoints?preset=1h",+ }+}++func buildApdexDropMessage(apdex float64, threshold float64, projectName string) Message {+ severity := SeverityWarning+ if apdex < 0.5 {+ severity = SeverityCritical+ }+ return Message{+ Subject: fmt.Sprintf("[%s] Apdex dropped to %.2f (threshold: %.2f)", projectName, apdex, threshold),+ Body: fmt.Sprintf("The Apdex score has dropped to %.2f (threshold: %.2f).", apdex, threshold),+ Severity: severity,+ URL: "/endpoints?preset=1h",+ }+}++func buildMetricThresholdMessage(metricName string, value float64, operator string, threshold float64, projectName string) Message {+ severity := SeverityWarning+ diff := value - threshold+ if diff < 0 {+ diff = -diff+ }+ if diff > threshold*0.2 {+ severity = SeverityCritical+ }+ return Message{+ Subject: fmt.Sprintf("[%s] Metric %s is %.2f (threshold: %s %.2f)", projectName, metricName, value, operator, threshold),+ Body: fmt.Sprintf("The metric %s has a value of %.2f which violates the threshold %s %.2f.", metricName, value, operator, threshold),+ Severity: severity,+ URL: "/metrics?preset=1h",+ }+}++func buildNoDataMessage(dataType string, silenceMinutes int, projectName string) Message {+ return Message{+ Subject: fmt.Sprintf("[%s] No %s data for %d minutes", projectName, dataType, silenceMinutes),+ Body: fmt.Sprintf("No %s data has been received for the last %d minutes.", dataType, silenceMinutes),+ Severity: SeverityCritical,+ URL: "/",+ }+}++func buildErrorCountMessage(count int64, threshold int64, window int, projectName string) Message {+ severity := SeverityWarning+ if count >= threshold*5 {+ severity = SeverityCritical+ }+ return Message{+ Subject: fmt.Sprintf("[%s] %d errors in last %d minutes", projectName, count, window),+ Body: fmt.Sprintf("There have been %d errors in the last %d minutes (threshold: %d).", count, window, threshold),+ Severity: severity,+ URL: "/issues?preset=1h",+ }+}++func buildTaskDurationMessage(taskName string, p95Ms float64, thresholdMs float64, projectName string) Message {+ return Message{+ Subject: fmt.Sprintf("[%s] Task %s P95 %.0fms exceeds %.0fms", projectName, taskName, p95Ms, thresholdMs),+ Body: fmt.Sprintf("The task %s P95 duration is %.0fms (threshold: %.0fms).", taskName, p95Ms, thresholdMs),+ Severity: SeverityWarning,+ URL: "/tasks?preset=1h",+ }+}++func buildThroughputDropMessage(dropPercent float64, projectName string) Message {+ severity := SeverityWarning+ if dropPercent >= 80 {+ severity = SeverityCritical+ }+ return Message{+ Subject: fmt.Sprintf("[%s] Throughput dropped %.0f%% vs baseline", projectName, dropPercent),+ Body: fmt.Sprintf("Request throughput has dropped by %.0f%% compared to the baseline window.", dropPercent),+ Severity: severity,+ URL: "/endpoints?preset=1h",+ }+}++func buildEndpointErrorRateMessage(endpoint string, rate float64, threshold float64, projectName string) Message {+ severity := SeverityWarning+ if rate >= threshold*2 {+ severity = SeverityCritical+ }+ return Message{+ Subject: fmt.Sprintf("[%s] %s error rate %.1f%%", projectName, endpoint, rate),+ Body: fmt.Sprintf("The endpoint %s has an error rate of %.1f%% (threshold: %.1f%%).", endpoint, rate, threshold),+ Severity: severity,+ URL: "/endpoints?preset=1h",+ }+}++func buildImpactScoreCriticalMessage(endpoint string, score float64, reason string, projectName string) Message {+ return Message{+ Subject: fmt.Sprintf("[%s] Endpoint %s impact became critical", projectName, endpoint),+ Body: fmt.Sprintf("The endpoint %s has become critical (impact score: %.2f). Reason: %s", endpoint, score, reason),+ Severity: SeverityCritical,+ URL: "/endpoints?preset=24h",+ Endpoint: endpoint,+ }+}++func buildImpactScoreHighMessage(endpoint string, score float64, reason string, projectName string) Message {+ return Message{+ Subject: fmt.Sprintf("[%s] Endpoint %s impact became high", projectName, endpoint),+ Body: fmt.Sprintf("The endpoint %s has become high impact (impact score: %.2f). Reason: %s", endpoint, score, reason),+ Severity: SeverityWarning,+ URL: "/endpoints?preset=24h",+ Endpoint: endpoint,+ }+}++func buildImpactScoreMediumMessage(endpoint string, score float64, reason string, projectName string) Message {+ return Message{+ Subject: fmt.Sprintf("[%s] Endpoint %s impact became medium", projectName, endpoint),+ Body: fmt.Sprintf("The endpoint %s has become medium impact (impact score: %.2f). Reason: %s", endpoint, score, reason),+ Severity: SeverityInfo,+ URL: "/endpoints?preset=24h",+ Endpoint: endpoint,+ }+}++func buildNewErrorMessage(errorType string, hash string, projectName string) Message {+ return Message{+ Subject: fmt.Sprintf("[%s] New error: %s", projectName, errorType),+ Body: fmt.Sprintf("A new error has been detected: %s", errorType),+ Severity: SeverityCritical,+ URL: fmt.Sprintf("/issues/%s", hash),+ }+}++func buildErrorRegressionMessage(errorType string, hash string, projectName string) Message {+ return Message{+ Subject: fmt.Sprintf("[%s] Resolved error reappeared: %s", projectName, errorType),+ Body: fmt.Sprintf("A previously resolved error has reappeared: %s", errorType),+ Severity: SeverityCritical,+ URL: fmt.Sprintf("/issues/%s", hash),+ }+}diff --git a/backend/app/repositories/endpoint.repository.go b/backend/app/repositories/endpoint.repository.goindex 93a3874c..ed60a363 100644--- a/backend/app/repositories/endpoint.repository.go+++ b/backend/app/repositories/endpoint.repository.go@@ -216,7 +216,7 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectIs.P95Duration = time.Duration(p95)s.P99Duration = time.Duration(p99)s.AvgDuration = time.Duration(avg)- s.ImpactReason = computeImpactReason(s.Endpoint, s.Count, satisfiedCount, toleratingCount, badCount, clientErrorCount, p99, offsetMs)+ s.ImpactReason = ComputeImpactReason(s.Endpoint, s.Count, satisfiedCount, toleratingCount, badCount, clientErrorCount, p99, offsetMs)stats = append(stats, s)}@@ -556,7 +556,7 @@ func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId us.P95Duration = time.Duration(p95)s.P99Duration = time.Duration(p99)s.AvgDuration = time.Duration(avg)- s.ImpactReason = computeImpactReason(s.Endpoint, s.Count, satisfiedCount, toleratingCount, badCount, clientErrorCount, p99, offsetMs)+ s.ImpactReason = ComputeImpactReason(s.Endpoint, s.Count, satisfiedCount, toleratingCount, badCount, clientErrorCount, p99, offsetMs)stats = append(stats, s)}diff --git a/backend/app/repositories/fired_notification.repository.go b/backend/app/repositories/fired_notification.repository.gonew file mode 100644index 00000000..a57d9c88--- /dev/null+++ b/backend/app/repositories/fired_notification.repository.go@@ -0,0 +1,48 @@+package repositories++import (+ "context"+ "time"++ "github.com/ClickHouse/clickhouse-go/v2"+ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/chdb"+)++type FiredNotification struct {+ ProjectId uuid.UUID+ RuleId int+ RuleType string+ RuleName string+ ChannelType string+ ChannelName string+ Severity string+ Subject string+ Body string+ Status string+ ErrorMsg string+ Endpoint string+ FiredAt time.Time+}++type firedNotificationRepository struct{}++func (r *firedNotificationRepository) Insert(ctx context.Context, n FiredNotification) error {+ batch, err := chdb.Conn.PrepareBatch(+ clickhouse.Context(context.Background(), clickhouse.WithAsync(false)),+ "INSERT INTO fired_notifications (project_id, rule_id, rule_type, rule_name, channel_type, channel_name, severity, subject, body, status, error_message, endpoint, fired_at)",+ )+ if err != nil {+ return err+ }+ if err := batch.Append(+ n.ProjectId, int32(n.RuleId), n.RuleType, n.RuleName,+ n.ChannelType, n.ChannelName, n.Severity, n.Subject, n.Body,+ n.Status, n.ErrorMsg, n.Endpoint, n.FiredAt,+ ); err != nil {+ return err+ }+ return batch.Send()+}++var FiredNotificationRepository = firedNotificationRepository{}diff --git a/backend/app/repositories/impact.go b/backend/app/repositories/impact.goindex 7ef19a92..7c38970d 100644--- a/backend/app/repositories/impact.go+++ b/backend/app/repositories/impact.go@@ -6,7 +6,7 @@ import ("time")-func computeImpactReason(+func ComputeImpactReason(endpoint string,total, satisfiedCount, toleratingCount, badCount, clientErrorCount uint64,p99Ns float64,diff --git a/backend/app/repositories/notification_channel.repository.go b/backend/app/repositories/notification_channel.repository.gonew file mode 100644index 00000000..d56c72e1--- /dev/null+++ b/backend/app/repositories/notification_channel.repository.go@@ -0,0 +1,51 @@+package repositories++import (+ "database/sql"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+)++type notificationChannelRepository struct{}++func (r *notificationChannelRepository) FindByProject(tx *sql.Tx, projectId uuid.UUID) ([]*models.NotificationChannel, error) {+ return lit.SelectNamed[models.NotificationChannel](+ tx,+ "SELECT id, project_id, name, channel_type, config, enabled, created_by, created_at, updated_at FROM notification_channels WHERE project_id = :project_id ORDER BY created_at DESC",+ lit.P{"project_id": projectId},+ )+}++func (r *notificationChannelRepository) FindById(tx *sql.Tx, id int) (*models.NotificationChannel, error) {+ return lit.SelectSingleNamed[models.NotificationChannel](+ tx,+ "SELECT id, project_id, name, channel_type, config, enabled, created_by, created_at, updated_at FROM notification_channels WHERE id = :id",+ lit.P{"id": id},+ )+}++func (r *notificationChannelRepository) Create(tx *sql.Tx, channel *models.NotificationChannel) (int, error) {+ return lit.Insert[models.NotificationChannel](tx, channel)+}++func (r *notificationChannelRepository) Update(tx *sql.Tx, channel *models.NotificationChannel) error {+ return lit.UpdateNamed(tx, channel, "id = :id", lit.P{"id": channel.Id})+}++func (r *notificationChannelRepository) Delete(tx *sql.Tx, id int) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM notification_channels WHERE id = :id", lit.P{"id": id})+}++func (r *notificationChannelRepository) FindEnabledByProject(tx *sql.Tx, projectId uuid.UUID) ([]*models.NotificationChannel, error) {+ return lit.SelectNamed[models.NotificationChannel](+ tx,+ "SELECT id, project_id, name, channel_type, config, enabled, created_by, created_at, updated_at FROM notification_channels WHERE project_id = :project_id AND enabled = true",+ lit.P{"project_id": projectId},+ )+}++var NotificationChannelRepository = notificationChannelRepository{}diff --git a/backend/app/repositories/notification_history.repository.go b/backend/app/repositories/notification_history.repository.gonew file mode 100644index 00000000..caf7e71a--- /dev/null+++ b/backend/app/repositories/notification_history.repository.go@@ -0,0 +1,55 @@+package repositories++import (+ "database/sql"++ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+)++type notificationHistoryRepository struct{}++func (r *notificationHistoryRepository) FindByProject(tx *sql.Tx, projectId uuid.UUID, page, pageSize int, search string) ([]*models.NotificationHistory, int64, error) {+ params := lit.P{"project_id": projectId}+ whereClause := "WHERE project_id = :project_id"++ if search != "" {+ whereClause += " AND (rule_name ILIKE :search OR channel_name ILIKE :search OR subject ILIKE :search)"+ params["search"] = "%" + search + "%"+ }++ countResult, err := lit.SelectSingleNamed[models.CountResult](+ tx,+ "SELECT COUNT(*) as count FROM notification_history "+whereClause,+ params,+ )+ if err != nil {+ return nil, 0, err+ }+ var total int64+ if countResult != nil {+ total = int64(countResult.Count)+ }++ offset := (page - 1) * pageSize+ params["limit"] = pageSize+ params["offset"] = offset+ items, err := lit.SelectNamed[models.NotificationHistory](+ tx,+ "SELECT id, project_id, rule_id, channel_id, rule_type, rule_name, channel_name, severity, subject, body, status, error_message, created_at FROM notification_history "+whereClause+" ORDER BY created_at DESC LIMIT :limit OFFSET :offset",+ params,+ )+ if err != nil {+ return nil, 0, err+ }++ return items, total, nil+}++func (r *notificationHistoryRepository) Create(tx *sql.Tx, history *models.NotificationHistory) (int, error) {+ return lit.Insert[models.NotificationHistory](tx, history)+}++var NotificationHistoryRepository = notificationHistoryRepository{}diff --git a/backend/app/repositories/notification_rule.repository.go b/backend/app/repositories/notification_rule.repository.gonew file mode 100644index 00000000..cb29a6bd--- /dev/null+++ b/backend/app/repositories/notification_rule.repository.go@@ -0,0 +1,90 @@+package repositories++import (+ "database/sql"+ "time"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+)++type notificationRuleRepository struct{}++func (r *notificationRuleRepository) FindByProjectWithChannel(tx *sql.Tx, projectId uuid.UUID) ([]*models.NotificationRuleWithChannel, error) {+ return lit.SelectNamed[models.NotificationRuleWithChannel](+ tx,+ `SELECT r.id, r.project_id, r.channel_id, r.name, r.rule_type, r.config, r.enabled, r.cooldown_minutes, r.snoozed_until, r.created_by, r.created_at, r.updated_at,+ c.name as channel_name, c.channel_type as channel_type+ FROM notification_rules r+ JOIN notification_channels c ON c.id = r.channel_id+ WHERE r.project_id = :project_id+ ORDER BY r.created_at DESC`,+ lit.P{"project_id": projectId},+ )+}++func (r *notificationRuleRepository) FindById(tx *sql.Tx, id int) (*models.NotificationRule, error) {+ return lit.SelectSingleNamed[models.NotificationRule](+ tx,+ "SELECT id, project_id, channel_id, name, rule_type, config, enabled, cooldown_minutes, snoozed_until, created_by, created_at, updated_at FROM notification_rules WHERE id = :id",+ lit.P{"id": id},+ )+}++func (r *notificationRuleRepository) FindEnabledPolledRules(tx *sql.Tx) ([]*models.NotificationRuleWithChannel, error) {+ return lit.Select[models.NotificationRuleWithChannel](+ tx,+ `SELECT r.id, r.project_id, r.channel_id, r.name, r.rule_type, r.config, r.enabled, r.cooldown_minutes, r.snoozed_until, r.created_by, r.created_at, r.updated_at,+ c.name as channel_name, c.channel_type as channel_type+ FROM notification_rules r+ JOIN notification_channels c ON c.id = r.channel_id+ WHERE r.enabled = true AND c.enabled = true+ AND r.rule_type NOT IN ('new_error', 'error_regression')`,+ )+}++func (r *notificationRuleRepository) FindEnabledEventRules(tx *sql.Tx, projectId uuid.UUID) ([]*models.NotificationRuleWithChannel, error) {+ return lit.SelectNamed[models.NotificationRuleWithChannel](+ tx,+ `SELECT r.id, r.project_id, r.channel_id, r.name, r.rule_type, r.config, r.enabled, r.cooldown_minutes, r.snoozed_until, r.created_by, r.created_at, r.updated_at,+ c.name as channel_name, c.channel_type as channel_type+ FROM notification_rules r+ JOIN notification_channels c ON c.id = r.channel_id+ WHERE r.project_id = :project_id AND r.enabled = true AND c.enabled = true+ AND r.rule_type IN ('new_error', 'error_regression')`,+ lit.P{"project_id": projectId},+ )+}++func (r *notificationRuleRepository) Create(tx *sql.Tx, rule *models.NotificationRule) (int, error) {+ return lit.Insert[models.NotificationRule](tx, rule)+}++func (r *notificationRuleRepository) Update(tx *sql.Tx, rule *models.NotificationRule) error {+ return lit.UpdateNamed(tx, rule, "id = :id", lit.P{"id": rule.Id})+}++func (r *notificationRuleRepository) Delete(tx *sql.Tx, id int) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM notification_rules WHERE id = :id", lit.P{"id": id})+}++func (r *notificationRuleRepository) UpdateEnabled(tx *sql.Tx, id int, enabled bool) error {+ q, a, err := lit.ParseNamedQuery(db.Driver, "UPDATE notification_rules SET enabled = :enabled, updated_at = NOW() WHERE id = :id", lit.P{"enabled": enabled, "id": id})+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, q, a...)+}++func (r *notificationRuleRepository) UpdateSnoozedUntil(tx *sql.Tx, id int, snoozedUntil *time.Time) error {+ q, a, err := lit.ParseNamedQuery(db.Driver, "UPDATE notification_rules SET snoozed_until = :snoozed_until, updated_at = NOW() WHERE id = :id", lit.P{"snoozed_until": snoozedUntil, "id": id})+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, q, a...)+}++var NotificationRuleRepository = notificationRuleRepository{}diff --git a/backend/cmd/run.go b/backend/cmd/run.goindex 0aaba33e..2848154f 100644--- a/backend/cmd/run.go+++ b/backend/cmd/run.go@@ -9,6 +9,7 @@ import ("github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/migrations""github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/notifications""github.com/tracewayapp/traceway/backend/app/services""github.com/tracewayapp/traceway/backend/app/storage""github.com/tracewayapp/traceway/backend/static"@@ -116,6 +117,8 @@ func Run(opts ...Option) {hook(ctx)}+ notifications.StartEvaluator(ctx)+var router *gin.Engineif o != nil && o.disableLogging {router = gin.New()diff --git a/docs/pages/learn/_meta.json b/docs/pages/learn/_meta.jsonindex a684e8f0..96a86f5c 100644--- a/docs/pages/learn/_meta.json+++ b/docs/pages/learn/_meta.json@@ -6,5 +6,6 @@"attributes": "Attributes","spans": "Spans","metrics": "Metrics",+ "alerts": "Alerts","embedded-mode": "Embedded Mode"}diff --git a/docs/pages/learn/alerts.mdx b/docs/pages/learn/alerts.mdxnew file mode 100644index 00000000..3402e701--- /dev/null+++ b/docs/pages/learn/alerts.mdx@@ -0,0 +1,108 @@+# Alerts++Alerts notify you when conditions in your application require attention — errors, latency spikes, metric thresholds, or missing data. Configure channels and rules to get notified through email, Slack, webhooks, or GitHub Issues.++## How Alerts Work++The alerting system has two parts:++- **Channels** define where notifications are delivered (email, Slack, webhook, GitHub)+- **Rules** define what conditions trigger a notification++When a rule's condition is met, Traceway sends a notification through the rule's attached channel. Each rule is linked to exactly one channel, but a channel can be used by multiple rules.++## Channels++A channel represents a notification destination. Traceway supports four channel types:++| Channel | Description | Configuration |+|---------|-------------|---------------|+| Email | Sends an email to one or more recipients | List of email addresses |+| Slack | Posts a message to a Slack channel via incoming webhook | Webhook URL |+| Webhook | Sends an HTTP POST with a JSON payload to any URL | URL, optional headers, optional HMAC secret |+| GitHub | Creates a GitHub issue in a repository | Personal access token, repository owner/name, optional labels |++Each channel has a **Test** button that sends a sample notification so you can verify the configuration before attaching rules.++### Webhook Payload++When a webhook channel fires, Traceway sends a JSON POST request with the following fields:++| Field | Description |+|-------|-------------|+| `subject` | Alert title |+| `body` | Alert details |+| `severity` | `info`, `warning`, or `critical` |+| `ruleType` | The rule type that triggered the alert |+| `ruleName` | The name you gave the rule |+| `url` | Deep link to the relevant dashboard page |+| `timestamp` | When the alert fired (ISO 8601) |++If you configure an HMAC secret on the channel, each request includes an `X-Traceway-Signature` header containing `sha256=<hex>` of the request body, which you can use to verify that the request came from Traceway.++## Rules++### Rule Types++| Rule | What It Monitors |+|------|-----------------|+| New Issue | A never-before-seen exception appears |+| Impact Score Critical | An endpoint's [impact score](/learn/endpoints#impact-score) reaches critical level |+| Impact Score High | An endpoint's impact score reaches high level |+| Impact Score Medium | An endpoint's impact score reaches medium level |++### Coming Soon++The following rule types are planned but not yet available:++- **Error Regression** — A previously resolved (archived) [issue](/learn/issues) reappears+- **Error Rate** — Overall 5xx error rate exceeds a percentage threshold+- **Error Count** — Total number of errors exceeds a count in a time window+- **Endpoint P95** — P95 latency for an endpoint exceeds a millisecond threshold+- **Endpoint P99** — P99 latency for an endpoint exceeds a millisecond threshold+- **Endpoint Error Rate** — A specific endpoint's error rate exceeds a percentage threshold+- **Apdex Drop** — Apdex score falls below a threshold+- **Metric Threshold** — A custom or system [metric](/learn/metrics) crosses a boundary (above or below)+- **No Data** — No telemetry data received for a specified duration+- **Task Duration** — A background task's P95 duration exceeds a threshold+- **Task Failure Rate** — A background task's failure rate exceeds a percentage threshold+- **Throughput Drop** — Request volume drops compared to baseline++### Evaluation++New Issue rules are evaluated immediately when new data arrives during report ingestion. Impact Score rules are evaluated every 60 seconds by a background process.++## Cooldown and Snooze++**Cooldown** prevents a rule from firing repeatedly for the same ongoing condition. After an alert fires, the rule will not fire again until the cooldown period expires. The default cooldown is 15 minutes, and it can be configured per rule.++**Snooze** lets you temporarily mute a rule for a set duration from the dashboard. This is useful during deployments, maintenance windows, or known incidents where you don't want to be notified.++## Severity++Each alert is assigned a severity level based on the condition:++| Severity | Typical Triggers |+|----------|-----------------|+| Critical | New errors, critical impact score |+| Warning | High impact score |+| Info | Medium impact score |++## History++All fired notifications are recorded and visible in the **History** tab on the Alerts page. Each entry shows:++| Field | Description |+|-------|-------------|+| Severity | Critical, warning, or info |+| Rule Name | The rule that triggered |+| Subject | Alert title summarizing the condition |+| Channel | Which channel delivered the notification |+| Status | Whether delivery succeeded or failed |+| Timestamp | When the notification was sent |+erity | Critical, warning, or info |+| Rule Name | The rule that triggered |+| Subject | Alert title summarizing the condition |+| Channel | Which channel delivered the notification |+| Status | Whether delivery succeeded or failed |+| Timestamp | When the notification was sent |diff --git a/frontend/src/lib/components/app-sidebar.svelte b/frontend/src/lib/components/app-sidebar.svelteindex 27cd3260..123297c1 100644--- a/frontend/src/lib/components/app-sidebar.svelte+++ b/frontend/src/lib/components/app-sidebar.svelte@@ -2,6 +2,7 @@import * as Sidebar from '$lib/components/ui/sidebar';import { useSidebar } from '$lib/components/ui/sidebar';import {+ Bell,Bug,Link2,ChartNoAxesCombined,@@ -40,6 +41,7 @@title: 'Metrics',stickyParams: ['preset', 'from', 'to']},+ { Icon: Bell, href: '/notifications', title: 'Alerts', stickyParams: [] },{ Icon: Link2, href: '/connection', title: 'Connection', stickyParams: [] }];diff --git a/frontend/src/routes/metrics/+page.svelte b/frontend/src/routes/metrics/+page.svelteindex 0360258e..79b62f95 100644--- a/frontend/src/routes/metrics/+page.svelte+++ b/frontend/src/routes/metrics/+page.svelte@@ -396,7 +396,7 @@</script><div class="space-y-4">- <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">+ <div class="mb-2 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between"><h2 class="text-2xl font-bold tracking-tight">Metrics</h2><div class="flex items-center gap-2"><TimeRangePickerdiff --git a/frontend/src/routes/notifications/+page.svelte b/frontend/src/routes/notifications/+page.sveltenew file mode 100644index 00000000..8f5ae6d0--- /dev/null+++ b/frontend/src/routes/notifications/+page.svelte@@ -0,0 +1,653 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { page } from '$app/state';+ import { goto } from '$app/navigation';+ import { api } from '$lib/api';+ import { projectsState } from '$lib/state/projects.svelte';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { Button } from '$lib/components/ui/button';+ import { Badge } from '$lib/components/ui/badge';+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';+ import { toast } from 'svelte-sonner';+ import * as Table from '$lib/components/ui/table';+ import * as Tabs from '$lib/components/ui/tabs';+ import * as Alert from '$lib/components/ui/alert';+ import * as AlertDialog from '$lib/components/ui/alert-dialog';+ import { Plus, Pencil, Trash2, Zap, ZapOff, Clock, Send, Info } from '@lucide/svelte';+ import { SearchBar } from '$lib/components/ui/search-bar';+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';++ import ChannelDialog from './channel-dialog.svelte';+ import RuleDialog from './rule-dialog.svelte';+ import SnoozeDialog from './snooze-dialog.svelte';++ interface NotificationChannel {+ id: number;+ projectId: string;+ name: string;+ channelType: string;+ config: any;+ enabled: boolean;+ createdAt: string;+ }++ interface NotificationRule {+ id: number;+ projectId: string;+ channelId: number;+ name: string;+ ruleType: string;+ config: any;+ enabled: boolean;+ cooldownMinutes: number;+ snoozedUntil: string | null;+ channelName: string;+ channelType: string;+ createdAt: string;+ }++ interface NotificationHistory {+ id: number;+ ruleType: string;+ ruleName: string;+ channelName: string;+ severity: string;+ subject: string;+ body: string;+ status: string;+ errorMessage: string | null;+ createdAt: string;+ }++ const ruleTypeLabels: Record<string, string> = {+ error_rate_threshold: 'Error Rate',+ endpoint_p95_threshold: 'Endpoint P95',+ endpoint_p99_threshold: 'Endpoint P99',+ apdex_drop: 'Apdex Drop',+ metric_threshold: 'Metric Threshold',+ no_data: 'No Data',+ error_count_threshold: 'Error Count',+ task_duration_threshold: 'Task Duration',+ task_failure_rate: 'Task Failure Rate',+ throughput_drop: 'Throughput Drop',+ endpoint_error_rate: 'Endpoint Error Rate',+ new_error: 'New Issue',+ error_regression: 'Error Regression',+ impact_score_critical: 'Impact Score Critical',+ impact_score_high: 'Impact Score High',+ impact_score_medium: 'Impact Score Medium'+ };++ const channelTypeLabels: Record<string, string> = {+ email: 'Email',+ webhook: 'Webhook',+ slack: 'Slack',+ github: 'GitHub'+ };++ const tabDescriptions: Record<string, string> = {+ channels:+ 'Channels define where your notifications are delivered — such as Email, Slack, Webhooks, or GitHub Issues. Create a channel first, then attach it to a rule.',+ rules: 'Rules define when notifications are triggered. Each rule monitors a specific condition and sends an alert through the attached channel when that condition is met.',+ history:+ 'A log of all notifications that have been sent, including their status and the rule that triggered them.'+ };++ const activeTab = $derived(page.url.searchParams.get('tab') || 'channels');++ function setTab(tab: string) {+ const url = new URL(window.location.href);+ url.searchParams.set('tab', tab);+ goto(url.toString(), { replaceState: true, noScroll: true });+ }++ let channels = $state<NotificationChannel[]>([]);+ let channelsLoading = $state(true);++ let rules = $state<NotificationRule[]>([]);+ let rulesLoading = $state(true);++ let history = $state<NotificationHistory[]>([]);+ let historyLoading = $state(true);+ let historyPage = $state(1);+ let historyPageSize = $state(25);+ let historyTotal = $state(0);+ let historyTotalPages = $state(0);+ let searchQuery = $state('');++ let channelDialogOpen = $state(false);+ let editingChannel = $state<NotificationChannel | null>(null);+ let ruleDialogOpen = $state(false);+ let editingRule = $state<NotificationRule | null>(null);+ let snoozeDialogOpen = $state(false);+ let snoozeRuleId = $state<number | null>(null);++ let showDeleteChannelDialog = $state(false);+ let deletingChannel = $state<NotificationChannel | null>(null);++ let showDeleteRuleDialog = $state(false);+ let deletingRule = $state<NotificationRule | null>(null);++ async function loadChannels() {+ channelsLoading = true;+ try {+ const res = await api.get('/notification-channels', {+ projectId: projectsState.currentProjectId ?? undefined+ });+ channels = res.channels || [];+ } catch {+ channels = [];+ } finally {+ channelsLoading = false;+ }+ }++ async function loadRules() {+ rulesLoading = true;+ try {+ const res = await api.get('/notification-rules', {+ projectId: projectsState.currentProjectId ?? undefined+ });+ rules = res.rules || [];+ } catch {+ rules = [];+ } finally {+ rulesLoading = false;+ }+ }++ async function loadHistory() {+ historyLoading = true;+ try {+ const res = await api.post(+ '/notification-history',+ {+ pagination: { page: historyPage, pageSize: historyPageSize },+ search: searchQuery.trim()+ },+ { projectId: projectsState.currentProjectId ?? undefined }+ );+ history = res.data || [];+ historyTotal = res.pagination?.total || 0;+ historyTotalPages = res.pagination?.totalPages || 0;+ } catch {+ history = [];+ } finally {+ historyLoading = false;+ }+ }++ function handleHistorySearch() {+ historyPage = 1;+ loadHistory();+ }++ function openDeleteChannel(channel: NotificationChannel) {+ deletingChannel = channel;+ showDeleteChannelDialog = true;+ }++ async function deleteChannel() {+ if (!deletingChannel) return;+ try {+ await api.delete(`/notification-channels/${deletingChannel.id}`, {+ projectId: projectsState.currentProjectId ?? undefined+ });+ toast.success('Successfully deleted the Channel', { position: 'top-center' });+ showDeleteChannelDialog = false;+ deletingChannel = null;+ loadChannels();+ loadRules();+ } catch {+ toast.error('Failed to delete channel', { position: 'top-center' });+ }+ }++ async function testChannel(id: number) {+ try {+ await api.post(+ `/notification-channels/${id}/test`,+ {},+ {+ projectId: projectsState.currentProjectId ?? undefined+ }+ );+ toast.success('Test notification sent', { position: 'top-center' });+ } catch (e: any) {+ toast.error(e.message || 'Test failed', { position: 'top-center' });+ }+ }++ function openDeleteRule(rule: NotificationRule) {+ deletingRule = rule;+ showDeleteRuleDialog = true;+ }++ async function deleteRule() {+ if (!deletingRule) return;+ try {+ await api.delete(`/notification-rules/${deletingRule.id}`, {+ projectId: projectsState.currentProjectId ?? undefined+ });+ toast.success('Successfully deleted the Rule', { position: 'top-center' });+ showDeleteRuleDialog = false;+ deletingRule = null;+ loadRules();+ } catch {+ toast.error('Failed to delete rule', { position: 'top-center' });+ }+ }++ async function toggleRule(id: number) {+ try {+ await api.post(+ `/notification-rules/${id}/toggle`,+ {},+ {+ projectId: projectsState.currentProjectId ?? undefined+ }+ );+ loadRules();+ } catch {+ toast.error('Failed to toggle rule', { position: 'top-center' });+ }+ }++ function openSnooze(id: number) {+ snoozeRuleId = id;+ snoozeDialogOpen = true;+ }++ function openEditChannel(channel: NotificationChannel) {+ editingChannel = channel;+ channelDialogOpen = true;+ }++ function openNewChannel() {+ editingChannel = null;+ channelDialogOpen = true;+ }++ function openEditRule(rule: NotificationRule) {+ editingRule = rule;+ ruleDialogOpen = true;+ }++ function openNewRule() {+ editingRule = null;+ ruleDialogOpen = true;+ }++ function formatDate(dateStr: string) {+ const date = new Date(dateStr);+ const now = new Date();+ const diff = now.getTime() - date.getTime();+ const minutes = Math.floor(diff / 60000);+ if (minutes < 1) return 'just now';+ if (minutes < 60) return `${minutes}m ago`;+ const hours = Math.floor(minutes / 60);+ if (hours < 24) return `${hours}h ago`;+ const days = Math.floor(hours / 24);+ return `${days}d ago`;+ }++ function isSnoozed(rule: NotificationRule) {+ return rule.snoozedUntil && new Date(rule.snoozedUntil) > new Date();+ }++ function handleHistoryPageChange(newPage: number) {+ historyPage = newPage;+ loadHistory();+ }++ function handleHistoryPageSizeChange(newSize: number) {+ historyPageSize = newSize;+ historyPage = 1;+ loadHistory();+ }++ onMount(() => {+ loadChannels();+ loadRules();+ loadHistory();+ });+</script>++<div class="space-y-2">+ <div>+ <h1 class="text-2xl font-semibold tracking-tight">Alerts</h1>+ </div>++ <div class="flex items-center justify-between">+ <Tabs.Root value={activeTab} onValueChange={(v) => { if (v) setTab(v); }}>+ <Tabs.List>+ <Tabs.Trigger value="channels">Channels</Tabs.Trigger>+ <Tabs.Trigger value="rules">Rules</Tabs.Trigger>+ <Tabs.Trigger value="history">History</Tabs.Trigger>+ </Tabs.List>+ </Tabs.Root>+ {#if activeTab === 'channels'}+ <Button size="sm" onclick={openNewChannel}>+ <Plus class="mr-1 h-4 w-4" /> New Channel+ </Button>+ {:else if activeTab === 'rules'}+ <Button size="sm" onclick={openNewRule}>+ <Plus class="mr-1 h-4 w-4" /> New Rule+ </Button>+ {/if}+ </div>++ <Alert.Root class="bg-blue-50 border-blue-200 text-blue-900 dark:bg-blue-950/50 dark:border-blue-800 dark:text-blue-200">+ <Info class="text-blue-600 dark:text-blue-400" />+ <Alert.Description class="text-blue-800 dark:text-blue-300">{tabDescriptions[activeTab]}</Alert.Description>+ </Alert.Root>++ {#if activeTab === 'channels'}+ {#if channelsLoading}+ <div class="flex justify-center py-12"><LoadingCircle size="xlg" /></div>+ {:else if channels.length === 0}+ <div+ class="flex flex-col items-center justify-center rounded-md bg-muted py-20 text-center text-muted-foreground"+ >+ <p class="mb-4">No channels yet. Create one to get started.</p>+ <Button onclick={openNewChannel}>+ <Plus class="mr-1 h-4 w-4" />+ Create your first Channel+ </Button>+ </div>+ {:else}+ <div class="overflow-hidden rounded-md border">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <Table.Head>Name</Table.Head>+ <Table.Head>Type</Table.Head>+ <Table.Head>Enabled</Table.Head>+ <Table.Head>Created</Table.Head>+ <Table.Head class="text-right">Actions</Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each channels as channel}+ <Table.Row>+ <Table.Cell class="font-medium">{channel.name}</Table.Cell>+ <Table.Cell>+ <Badge variant="outline"+ >{channelTypeLabels[channel.channelType] ||+ channel.channelType}</Badge+ >+ </Table.Cell>+ <Table.Cell>+ {#if channel.enabled}+ <Badge variant="default" class="bg-green-600">On</Badge>+ {:else}+ <Badge variant="secondary">Off</Badge>+ {/if}+ </Table.Cell>+ <Table.Cell class="text-muted-foreground"+ >{formatDate(channel.createdAt)}</Table.Cell+ >+ <Table.Cell class="text-right">+ <div class="flex justify-end gap-1">+ <Button+ variant="ghost"+ size="icon"+ onclick={() => testChannel(channel.id)}+ title="Test"+ >+ <Send class="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ onclick={() => openEditChannel(channel)}+ title="Edit"+ >+ <Pencil class="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ onclick={() => openDeleteChannel(channel)}+ title="Delete"+ >+ <Trash2 class="h-4 w-4" />+ </Button>+ </div>+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </div>+ {/if}+ {:else if activeTab === 'rules'}+ {#if rulesLoading}+ <div class="flex justify-center py-12"><LoadingCircle size="xlg" /></div>+ {:else if rules.length === 0}+ <div+ class="flex flex-col items-center justify-center rounded-md bg-muted py-20 text-center text-muted-foreground"+ >+ <p class="mb-4">No rules yet. Create one to get started.</p>+ <Button onclick={openNewRule}>+ <Plus class="mr-1 h-4 w-4" />+ Create your first Rule+ </Button>+ </div>+ {:else}+ <div class="overflow-hidden rounded-md border">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <Table.Head>Name</Table.Head>+ <Table.Head>Type</Table.Head>+ <Table.Head>Channel</Table.Head>+ <Table.Head>Status</Table.Head>+ <Table.Head class="text-right">Actions</Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each rules as rule}+ <Table.Row>+ <Table.Cell class="font-medium">{rule.name}</Table.Cell>+ <Table.Cell+ >{ruleTypeLabels[rule.ruleType] || rule.ruleType}</Table.Cell+ >+ <Table.Cell>+ <Badge variant="outline">{rule.channelName}</Badge>+ </Table.Cell>+ <Table.Cell>+ {#if isSnoozed(rule)}+ <Badge variant="secondary">Snoozed</Badge>+ {:else if rule.enabled}+ <Badge variant="default" class="bg-green-600">On</Badge>+ {:else}+ <Badge variant="secondary">Off</Badge>+ {/if}+ </Table.Cell>+ <Table.Cell class="text-right">+ <div class="flex justify-end gap-1">+ <Button+ variant="ghost"+ size="icon"+ onclick={() => openSnooze(rule.id)}+ title="Snooze"+ >+ <Clock class="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ onclick={() => toggleRule(rule.id)}+ title={rule.enabled ? 'Disable' : 'Enable'}+ >+ {#if rule.enabled}+ <ZapOff class="h-4 w-4" />+ {:else}+ <Zap class="h-4 w-4" />+ {/if}+ </Button>+ <Button+ variant="ghost"+ size="icon"+ onclick={() => openEditRule(rule)}+ title="Edit"+ >+ <Pencil class="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ onclick={() => openDeleteRule(rule)}+ title="Delete"+ >+ <Trash2 class="h-4 w-4" />+ </Button>+ </div>+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </div>+ {/if}+ {:else if activeTab === 'history'}+ <div class="pt-2">+ <SearchBar+ placeholder="Search Historic Alerts..."+ bind:value={searchQuery}+ onSearch={handleHistorySearch}+ disabled={historyLoading}+ />+ </div>++ <div class="overflow-hidden rounded-md border">+ <Table.Root>+ {#if historyLoading}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={6} class="h-48">+ <div class="flex h-full items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if history.length === 0}+ <Table.Body>+ <TableEmptyState colspan={6} message="No Historic Alerts found." />+ </Table.Body>+ {:else}+ <Table.Header>+ <Table.Row>+ <Table.Head>Severity</Table.Head>+ <Table.Head>Rule</Table.Head>+ <Table.Head>Subject</Table.Head>+ <Table.Head>Channel</Table.Head>+ <Table.Head>Status</Table.Head>+ <Table.Head>Sent At</Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each history as item}+ <Table.Row>+ <Table.Cell>+ {#if item.severity === 'critical'}+ <Badge variant="destructive">Critical</Badge>+ {:else if item.severity === 'warning'}+ <Badge class="bg-amber-500 text-white">Warning</Badge>+ {:else}+ <Badge variant="secondary">Info</Badge>+ {/if}+ </Table.Cell>+ <Table.Cell class="font-medium">{item.ruleName}</Table.Cell>+ <Table.Cell class="max-w-xs truncate">{item.subject}</Table.Cell>+ <Table.Cell>{item.channelName}</Table.Cell>+ <Table.Cell>+ {#if item.status === 'sent'}+ <Badge class="bg-green-600 text-white">Sent</Badge>+ {:else if item.status === 'failed'}+ <Badge variant="destructive">Failed</Badge>+ {:else}+ <Badge variant="secondary">Skipped</Badge>+ {/if}+ </Table.Cell>+ <Table.Cell class="text-muted-foreground"+ >{formatDate(item.createdAt)}</Table.Cell+ >+ </Table.Row>+ {/each}+ </Table.Body>+ {/if}+ </Table.Root>+ </div>++ <PaginationFooter+ currentPage={historyPage}+ totalPages={historyTotalPages}+ pageSize={historyPageSize}+ totalItems={historyTotal}+ onPageChange={handleHistoryPageChange}+ onPageSizeChange={handleHistoryPageSizeChange}+ itemLabel="notification"+ />+ {/if}+</div>++<ChannelDialog+ bind:open={channelDialogOpen}+ channel={editingChannel}+ onSaved={() => {+ loadChannels();+ channelDialogOpen = false;+ }}+/>++<RuleDialog+ bind:open={ruleDialogOpen}+ rule={editingRule}+ {channels}+ onSaved={() => {+ loadRules();+ ruleDialogOpen = false;+ }}+/>++<SnoozeDialog+ bind:open={snoozeDialogOpen}+ ruleId={snoozeRuleId}+ onSaved={() => {+ loadRules();+ snoozeDialogOpen = false;+ }}+/>++<AlertDialog.Root bind:open={showDeleteChannelDialog}>+ <AlertDialog.Content interactOutsideBehavior="close">+ <AlertDialog.Header>+ <AlertDialog.Title>Delete Channel</AlertDialog.Title>+ <AlertDialog.Description>+ Are you sure you want to delete "{deletingChannel?.name}"? This action cannot be undone.+ </AlertDialog.Description>+ </AlertDialog.Header>+ <AlertDialog.Footer>+ <Button variant="outline" onclick={() => (showDeleteChannelDialog = false)}>Cancel</Button>+ <Button variant="destructive" onclick={deleteChannel}>Delete</Button>+ </AlertDialog.Footer>+ </AlertDialog.Content>+</AlertDialog.Root>++<AlertDialog.Root bind:open={showDeleteRuleDialog}>+ <AlertDialog.Content interactOutsideBehavior="close">+ <AlertDialog.Header>+ <AlertDialog.Title>Delete Rule</AlertDialog.Title>+ <AlertDialog.Description>+ Are you sure you want to delete "{deletingRule?.name}"? This action cannot be undone.+ </AlertDialog.Description>+ </AlertDialog.Header>+ <AlertDialog.Footer>+ <Button variant="outline" onclick={() => (showDeleteRuleDialog = false)}>Cancel</Button>+ <Button variant="destructive" onclick={deleteRule}>Delete</Button>+ </AlertDialog.Footer>+ </AlertDialog.Content>+</AlertDialog.Root>diff --git a/frontend/src/routes/notifications/channel-dialog.svelte b/frontend/src/routes/notifications/channel-dialog.sveltenew file mode 100644index 00000000..34e1b95a--- /dev/null+++ b/frontend/src/routes/notifications/channel-dialog.svelte@@ -0,0 +1,406 @@+<script lang="ts">+ import * as AlertDialog from '$lib/components/ui/alert-dialog';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import * as Select from '$lib/components/ui/select';+ import { Plus, Check, Trash2 } from '@lucide/svelte';+ import { toast } from 'svelte-sonner';+ import { api } from '$lib/api';+ import { projectsState } from '$lib/state/projects.svelte';++ interface NotificationChannel {+ id: number;+ projectId: string;+ name: string;+ channelType: string;+ config: any;+ enabled: boolean;+ createdAt: string;+ }++ interface Props {+ open: boolean;+ channel: NotificationChannel | null;+ onSaved: () => void;+ }++ let { open = $bindable(), channel, onSaved }: Props = $props();++ let name = $state('');+ let channelType = $state('email');+ let loading = $state(false);+ let error = $state('');++ let emailRecipients = $state<string[]>(['']);+ let webhookUrl = $state('');+ let webhookMethod = $state('POST');+ let webhookSecret = $state('');+ let webhookHeaders = $state<{ key: string; value: string }[]>([]);+ let slackWebhookUrl = $state('');+ let slackChannel = $state('');+ let slackUsername = $state('');+ let githubToken = $state('');+ let githubOwner = $state('');+ let githubRepo = $state('');+ let githubLabels = $state('');++ const isEditing = $derived(channel !== null);++ const channelTypeOptions = [+ { value: 'email', label: 'Email' },+ { value: 'webhook', label: 'Webhook' },+ { value: 'slack', label: 'Slack' },+ { value: 'github', label: 'GitHub' }+ ];++ function resetForm() {+ name = '';+ channelType = 'email';+ error = '';+ emailRecipients = [''];+ webhookUrl = '';+ webhookMethod = 'POST';+ webhookSecret = '';+ webhookHeaders = [];+ slackWebhookUrl = '';+ slackChannel = '';+ slackUsername = '';+ githubToken = '';+ githubOwner = '';+ githubRepo = '';+ githubLabels = '';+ }++ function populateFromChannel(ch: NotificationChannel) {+ name = ch.name;+ channelType = ch.channelType;+ const config = ch.config || {};++ if (ch.channelType === 'email') {+ emailRecipients = config.recipients?.length ? [...config.recipients] : [''];+ } else if (ch.channelType === 'webhook') {+ webhookUrl = config.url || '';+ webhookMethod = config.method || 'POST';+ webhookSecret = config.secret || '';+ webhookHeaders = config.headers+ ? Object.entries(config.headers).map(([key, value]) => ({+ key,+ value: value as string+ }))+ : [];+ } else if (ch.channelType === 'slack') {+ slackWebhookUrl = config.webhookUrl || '';+ slackChannel = config.channel || '';+ slackUsername = config.username || '';+ } else if (ch.channelType === 'github') {+ githubToken = config.token || '';+ githubOwner = config.owner || '';+ githubRepo = config.repo || '';+ githubLabels = (config.labels || []).join(', ');+ }+ }++ function buildConfig(): any {+ if (channelType === 'email') {+ return { recipients: emailRecipients.filter((e) => e.trim() !== '') };+ } else if (channelType === 'webhook') {+ const config: any = { url: webhookUrl };+ if (webhookMethod !== 'POST') config.method = webhookMethod;+ if (webhookSecret) config.secret = webhookSecret;+ const headers: Record<string, string> = {};+ for (const h of webhookHeaders) {+ if (h.key.trim()) headers[h.key.trim()] = h.value;+ }+ if (Object.keys(headers).length > 0) config.headers = headers;+ return config;+ } else if (channelType === 'slack') {+ const config: any = { webhookUrl: slackWebhookUrl };+ if (slackChannel) config.channel = slackChannel;+ if (slackUsername) config.username = slackUsername;+ return config;+ } else if (channelType === 'github') {+ const config: any = {+ token: githubToken,+ owner: githubOwner,+ repo: githubRepo+ };+ const labels = githubLabels+ .split(',')+ .map((l) => l.trim())+ .filter((l) => l);+ if (labels.length > 0) config.labels = labels;+ return config;+ }+ return {};+ }++ function addEmailRecipient() {+ emailRecipients = [...emailRecipients, ''];+ }++ function removeEmailRecipient(index: number) {+ emailRecipients = emailRecipients.filter((_, i) => i !== index);+ if (emailRecipients.length === 0) emailRecipients = [''];+ }++ function addWebhookHeader() {+ webhookHeaders = [...webhookHeaders, { key: '', value: '' }];+ }++ function removeWebhookHeader(index: number) {+ webhookHeaders = webhookHeaders.filter((_, i) => i !== index);+ }++ async function handleSubmit() {+ loading = true;+ error = '';++ try {+ const body = {+ name,+ channelType,+ config: buildConfig()+ };++ if (isEditing) {+ await api.put(`/notification-channels/${channel!.id}`, body, {+ projectId: projectsState.currentProjectId ?? undefined+ });+ toast.success('Successfully updated the Channel', { position: 'top-center' });+ } else {+ await api.post('/notification-channels', body, {+ projectId: projectsState.currentProjectId ?? undefined+ });+ toast.success('Successfully created the Channel', { position: 'top-center' });+ }+ onSaved();+ } catch (e: unknown) {+ error = e instanceof Error ? e.message : 'Failed to save channel';+ } finally {+ loading = false;+ }+ }++ function handleOpenChange(isOpen: boolean) {+ if (!isOpen) {+ resetForm();+ } else if (channel) {+ populateFromChannel(channel);+ } else {+ resetForm();+ }+ open = isOpen;+ }++ $effect(() => {+ if (open && channel) {+ populateFromChannel(channel);+ } else if (open && !channel) {+ resetForm();+ }+ });+</script>++<AlertDialog.Root {open} onOpenChange={handleOpenChange}>+ <AlertDialog.Content class="max-w-md">+ <AlertDialog.Header>+ <AlertDialog.Title>{isEditing ? 'Edit Channel' : 'New Channel'}</AlertDialog.Title>+ <AlertDialog.Description>+ {isEditing+ ? 'Update the notification channel configuration'+ : 'Configure a new notification channel'}+ </AlertDialog.Description>+ </AlertDialog.Header>++ <form+ onsubmit={(e) => {+ e.preventDefault();+ handleSubmit();+ }}+ class="space-y-4"+ >+ <div class="space-y-2">+ <Label for="channel-name">Name</Label>+ <Input id="channel-name" bind:value={name} placeholder="e.g. Team Slack" required />+ </div>++ <div class="space-y-2">+ <Label for="channel-type">Type</Label>+ <Select.Root type="single" bind:value={channelType}>+ <Select.Trigger class="w-full">+ {channelTypeOptions.find((o) => o.value === channelType)?.label ||+ 'Select type'}+ </Select.Trigger>+ <Select.Content>+ {#each channelTypeOptions as option}+ <Select.Item value={option.value}>{option.label}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>++ {#if channelType === 'email'}+ <div class="space-y-2">+ <Label>Recipients</Label>+ {#each emailRecipients as _, index}+ <div class="flex gap-2">+ <Input+ type="email"+ bind:value={emailRecipients[index]}+ placeholder="[email protected]"+ />+ {#if emailRecipients.length > 1}+ <Button+ variant="ghost"+ size="icon"+ type="button"+ onclick={() => removeEmailRecipient(index)}+ >+ <Trash2 class="h-4 w-4" />+ </Button>+ {/if}+ </div>+ {/each}+ {#if emailRecipients.length < 10}+ <Button variant="outline" size="sm" type="button" onclick={addEmailRecipient}>+ <Plus class="mr-1 h-3 w-3" /> Add Recipient+ </Button>+ {/if}+ </div>+ {:else if channelType === 'webhook'}+ <div class="space-y-2">+ <Label for="webhook-url">URL</Label>+ <Input+ id="webhook-url"+ bind:value={webhookUrl}+ placeholder="https://example.com/webhook"+ required+ />+ </div>+ <div class="space-y-2">+ <Label for="webhook-method">Method</Label>+ <Select.Root type="single" bind:value={webhookMethod}>+ <Select.Trigger class="w-full">+ {webhookMethod}+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="POST">POST</Select.Item>+ <Select.Item value="PUT">PUT</Select.Item>+ </Select.Content>+ </Select.Root>+ </div>+ <div class="space-y-2">+ <Label for="webhook-secret">Secret (optional)</Label>+ <Input+ id="webhook-secret"+ bind:value={webhookSecret}+ placeholder="HMAC signing secret"+ />+ </div>+ <div class="space-y-2">+ <Label>Headers (optional)</Label>+ {#each webhookHeaders as _, index}+ <div class="flex gap-2">+ <Input+ bind:value={webhookHeaders[index].key}+ placeholder="Header name"+ class="flex-1"+ />+ <Input+ bind:value={webhookHeaders[index].value}+ placeholder="Value"+ class="flex-1"+ />+ <Button+ variant="ghost"+ size="icon"+ type="button"+ onclick={() => removeWebhookHeader(index)}+ >+ <Trash2 class="h-4 w-4" />+ </Button>+ </div>+ {/each}+ <Button variant="outline" size="sm" type="button" onclick={addWebhookHeader}>+ <Plus class="mr-1 h-3 w-3" /> Add Header+ </Button>+ </div>+ {:else if channelType === 'slack'}+ <div class="space-y-2">+ <Label for="slack-url">Webhook URL</Label>+ <Input+ id="slack-url"+ bind:value={slackWebhookUrl}+ placeholder="https://hooks.slack.com/services/..."+ required+ />+ </div>+ <div class="space-y-2">+ <Label for="slack-channel">Channel Override (optional)</Label>+ <Input+ id="slack-channel"+ bind:value={slackChannel}+ placeholder="#alerts"+ />+ </div>+ <div class="space-y-2">+ <Label for="slack-username">Username (optional)</Label>+ <Input+ id="slack-username"+ bind:value={slackUsername}+ placeholder="Traceway"+ />+ </div>+ {:else if channelType === 'github'}+ <div class="space-y-2">+ <Label for="gh-token">Personal Access Token</Label>+ <Input+ id="gh-token"+ type="password"+ bind:value={githubToken}+ placeholder="ghp_..."+ required+ />+ </div>+ <div class="space-y-2">+ <Label for="gh-owner">Repository Owner</Label>+ <Input id="gh-owner" bind:value={githubOwner} placeholder="owner" required />+ </div>+ <div class="space-y-2">+ <Label for="gh-repo">Repository Name</Label>+ <Input id="gh-repo" bind:value={githubRepo} placeholder="repo" required />+ </div>+ <div class="space-y-2">+ <Label for="gh-labels">Labels (optional, comma-separated)</Label>+ <Input id="gh-labels" bind:value={githubLabels} placeholder="bug, traceway" />+ </div>+ {/if}++ {#if error}+ <p class="text-sm text-destructive">{error}</p>+ {/if}+ </form>++ <AlertDialog.Footer>+ <AlertDialog.Cancel disabled={loading}>Cancel</AlertDialog.Cancel>+ <Button onclick={handleSubmit} disabled={loading}>+ {#if isEditing}+ <Check class="mr-2 h-4 w-4" />+ {#if loading}+ Updating...+ {:else}+ Update Channel+ {/if}+ {:else}+ <Plus class="mr-2 h-4 w-4" />+ {#if loading}+ Creating...+ {:else}+ New Channel+ {/if}+ {/if}+ </Button>+ </AlertDialog.Footer>+ </AlertDialog.Content>+</AlertDialog.Root>diff --git a/frontend/src/routes/notifications/rule-dialog.svelte b/frontend/src/routes/notifications/rule-dialog.sveltenew file mode 100644index 00000000..ded4a376--- /dev/null+++ b/frontend/src/routes/notifications/rule-dialog.svelte@@ -0,0 +1,776 @@+<script lang="ts">+ import * as AlertDialog from '$lib/components/ui/alert-dialog';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import * as Select from '$lib/components/ui/select';+ import { Plus, Check, TriangleAlert } from '@lucide/svelte';+ import * as Alert from '$lib/components/ui/alert';+ import { toast } from 'svelte-sonner';+ import { api } from '$lib/api';+ import { projectsState } from '$lib/state/projects.svelte';++ interface NotificationChannel {+ id: number;+ projectId: string;+ name: string;+ channelType: string;+ config: any;+ enabled: boolean;+ createdAt: string;+ }++ interface NotificationRule {+ id: number;+ projectId: string;+ channelId: number;+ name: string;+ ruleType: string;+ config: any;+ enabled: boolean;+ cooldownMinutes: number;+ snoozedUntil: string | null;+ channelName: string;+ channelType: string;+ createdAt: string;+ }++ interface Props {+ open: boolean;+ rule: NotificationRule | null;+ channels: NotificationChannel[];+ onSaved: () => void;+ }++ let { open = $bindable(), rule, channels, onSaved }: Props = $props();++ let name = $state('');+ let channelId = $state('');+ let ruleType = $state('new_error');+ let cooldownMinutes = $state(15);+ let loading = $state(false);+ let error = $state('');++ let thresholdPercent = $state(5);+ let lookbackMinutes = $state(5);+ let minRequests = $state(10);+ let endpoint = $state('*');+ let thresholdMs = $state(500);+ let thresholdApdex = $state(0.85);+ let metricName = $state('');+ let operator = $state('gt');+ let thresholdValue = $state(90);+ let aggregation = $state('avg');+ let dataType = $state('any');+ let silenceMinutes = $state(10);+ let thresholdCount = $state(100);+ let taskName = $state('*');+ let minExecutions = $state(5);+ let dropPercent = $state(50);+ let baselineWindowMinutes = $state(60);+ let ignorePatterns = $state('');+ let includeArchived = $state(true);++ const isEditing = $derived(rule !== null);++ const ruleTypeOptions = [+ { value: 'new_error', label: 'New Issue' },+ { value: 'impact_score_critical', label: 'Impact Score Critical' },+ { value: 'impact_score_high', label: 'Impact Score High' },+ { value: 'impact_score_medium', label: 'Impact Score Medium' },+ { value: 'error_regression', label: 'Error Regression' },+ { value: 'error_rate_threshold', label: 'Error Rate' },+ { value: 'error_count_threshold', label: 'Error Count' },+ { value: 'endpoint_p95_threshold', label: 'Endpoint P95' },+ { value: 'endpoint_p99_threshold', label: 'Endpoint P99' },+ { value: 'endpoint_error_rate', label: 'Endpoint Error Rate' },+ { value: 'apdex_drop', label: 'Apdex Drop' },+ { value: 'metric_threshold', label: 'Metric Threshold' },+ { value: 'no_data', label: 'No Data' },+ { value: 'task_duration_threshold', label: 'Task Duration' },+ { value: 'task_failure_rate', label: 'Task Failure Rate' },+ { value: 'throughput_drop', label: 'Throughput Drop' }+ ];++ const ruleTypeDescriptions: Record<string, string> = {+ new_error:+ 'Fires when a completely new error type is detected for the first time in your project.',+ impact_score_critical:+ 'Fires when an endpoint\u2019s impact score reaches critical level (\u2265 0.75), indicating severe performance or reliability degradation.',+ impact_score_high:+ 'Fires when an endpoint\u2019s impact score reaches high level (\u2265 0.50), indicating significant performance or reliability issues.',+ impact_score_medium:+ 'Fires when an endpoint\u2019s impact score reaches medium level (\u2265 0.25), an early warning of emerging performance or reliability issues.'+ };++ const operatorOptions = [+ { value: 'gt', label: '> Greater than' },+ { value: 'gte', label: '>= Greater or equal' },+ { value: 'lt', label: '< Less than' },+ { value: 'lte', label: '<= Less or equal' },+ { value: 'eq', label: '= Equal' }+ ];++ const aggregationOptions = [+ { value: 'avg', label: 'Average' },+ { value: 'max', label: 'Maximum' },+ { value: 'min', label: 'Minimum' },+ { value: 'sum', label: 'Sum' },+ { value: 'p95', label: 'P95' },+ { value: 'p99', label: 'P99' },+ { value: 'last', label: 'Last' }+ ];++ const dataTypeOptions = [+ { value: 'any', label: 'Any' },+ { value: 'endpoints', label: 'Endpoints' },+ { value: 'exceptions', label: 'Exceptions' },+ { value: 'metrics', label: 'Metrics' },+ { value: 'tasks', label: 'Tasks' }+ ];++ function resetForm() {+ name = '';+ channelId = '';+ ruleType = 'new_error';+ cooldownMinutes = 15;+ error = '';+ thresholdPercent = 5;+ lookbackMinutes = 5;+ minRequests = 10;+ endpoint = '*';+ thresholdMs = 500;+ thresholdApdex = 0.85;+ metricName = '';+ operator = 'gt';+ thresholdValue = 90;+ aggregation = 'avg';+ dataType = 'any';+ silenceMinutes = 10;+ thresholdCount = 100;+ taskName = '*';+ minExecutions = 5;+ dropPercent = 50;+ baselineWindowMinutes = 60;+ ignorePatterns = '';+ includeArchived = true;+ }++ function populateFromRule(r: NotificationRule) {+ name = r.name;+ channelId = r.channelId.toString();+ ruleType = r.ruleType;+ cooldownMinutes = r.cooldownMinutes;+ const cfg = r.config || {};++ switch (r.ruleType) {+ case 'error_rate_threshold':+ thresholdPercent = cfg.thresholdPercent ?? 5;+ lookbackMinutes = cfg.lookbackMinutes ?? 5;+ minRequests = cfg.minRequests ?? 10;+ break;+ case 'endpoint_p95_threshold':+ case 'endpoint_p99_threshold':+ endpoint = cfg.endpoint ?? '*';+ thresholdMs = cfg.thresholdMs ?? 500;+ lookbackMinutes = cfg.lookbackMinutes ?? 5;+ break;+ case 'apdex_drop':+ thresholdApdex = cfg.thresholdApdex ?? 0.85;+ lookbackMinutes = cfg.lookbackMinutes ?? 15;+ minRequests = cfg.minRequests ?? 50;+ break;+ case 'metric_threshold':+ metricName = cfg.metricName ?? '';+ operator = cfg.operator ?? 'gt';+ thresholdValue = cfg.thresholdValue ?? 90;+ aggregation = cfg.aggregation ?? 'avg';+ lookbackMinutes = cfg.lookbackMinutes ?? 5;+ break;+ case 'no_data':+ dataType = cfg.dataType ?? 'any';+ silenceMinutes = cfg.silenceMinutes ?? 10;+ break;+ case 'error_count_threshold':+ thresholdCount = cfg.thresholdCount ?? 100;+ lookbackMinutes = cfg.lookbackMinutes ?? 60;+ break;+ case 'task_duration_threshold':+ taskName = cfg.taskName ?? '*';+ thresholdMs = cfg.thresholdMs ?? 30000;+ lookbackMinutes = cfg.lookbackMinutes ?? 30;+ break;+ case 'task_failure_rate':+ taskName = cfg.taskName ?? '*';+ thresholdPercent = cfg.thresholdPercent ?? 10;+ lookbackMinutes = cfg.lookbackMinutes ?? 60;+ minExecutions = cfg.minExecutions ?? 5;+ break;+ case 'throughput_drop':+ dropPercent = cfg.dropPercent ?? 50;+ lookbackMinutes = cfg.lookbackMinutes ?? 15;+ baselineWindowMinutes = cfg.baselineWindowMinutes ?? 60;+ break;+ case 'endpoint_error_rate':+ endpoint = cfg.endpoint ?? '*';+ thresholdPercent = cfg.thresholdPercent ?? 2;+ lookbackMinutes = cfg.lookbackMinutes ?? 10;+ minRequests = cfg.minRequests ?? 20;+ break;+ case 'new_error':+ ignorePatterns = (cfg.ignorePatterns || []).join(', ');+ break;+ case 'error_regression':+ includeArchived = cfg.includeArchived ?? true;+ break;+ case 'impact_score_critical':+ case 'impact_score_high':+ case 'impact_score_medium':+ minRequests = cfg.minRequests ?? 50;+ break;+ }+ }++ function buildConfig(): any {+ switch (ruleType) {+ case 'error_rate_threshold':+ return { thresholdPercent, lookbackMinutes, minRequests };+ case 'endpoint_p95_threshold':+ case 'endpoint_p99_threshold':+ return { endpoint, thresholdMs, lookbackMinutes };+ case 'apdex_drop':+ return { thresholdApdex, lookbackMinutes, minRequests };+ case 'metric_threshold':+ return { metricName, operator, thresholdValue, aggregation, lookbackMinutes, tags: {} };+ case 'no_data':+ return { dataType, silenceMinutes };+ case 'error_count_threshold':+ return { thresholdCount, lookbackMinutes };+ case 'task_duration_threshold':+ return { taskName, thresholdMs, lookbackMinutes };+ case 'task_failure_rate':+ return { taskName, thresholdPercent, lookbackMinutes, minExecutions };+ case 'throughput_drop':+ return { dropPercent, lookbackMinutes, baselineWindowMinutes };+ case 'endpoint_error_rate':+ return { endpoint, thresholdPercent, lookbackMinutes, minRequests };+ case 'new_error': {+ const patterns = ignorePatterns+ .split(',')+ .map((p) => p.trim())+ .filter((p) => p);+ return { ignorePatterns: patterns };+ }+ case 'error_regression':+ return { includeArchived };+ case 'impact_score_critical':+ case 'impact_score_high':+ case 'impact_score_medium':+ return { minRequests };+ default:+ return {};+ }+ }++ async function handleSubmit() {+ loading = true;+ error = '';++ try {+ const body = {+ channelId: parseInt(channelId),+ name,+ ruleType,+ config: buildConfig(),+ cooldownMinutes+ };++ if (isEditing) {+ await api.put(`/notification-rules/${rule!.id}`, body, {+ projectId: projectsState.currentProjectId ?? undefined+ });+ toast.success('Successfully updated the Rule', { position: 'top-center' });+ } else {+ await api.post('/notification-rules', body, {+ projectId: projectsState.currentProjectId ?? undefined+ });+ toast.success('Successfully created the Rule', { position: 'top-center' });+ }+ onSaved();+ } catch (e: unknown) {+ error = e instanceof Error ? e.message : 'Failed to save rule';+ } finally {+ loading = false;+ }+ }++ function handleOpenChange(isOpen: boolean) {+ if (!isOpen) {+ resetForm();+ } else if (rule) {+ populateFromRule(rule);+ } else {+ resetForm();+ }+ open = isOpen;+ }++ $effect(() => {+ if (open && rule) {+ populateFromRule(rule);+ } else if (open && !rule) {+ resetForm();+ }+ });+</script>++<AlertDialog.Root {open} onOpenChange={handleOpenChange}>+ <AlertDialog.Content class="max-w-lg max-h-[85vh] overflow-y-auto">+ <AlertDialog.Header>+ <AlertDialog.Title>{isEditing ? 'Edit Rule' : 'New Rule'}</AlertDialog.Title>+ <AlertDialog.Description>+ {isEditing+ ? 'Update the notification rule configuration'+ : 'Configure a new notification rule'}+ </AlertDialog.Description>+ </AlertDialog.Header>++ <form+ onsubmit={(e) => {+ e.preventDefault();+ handleSubmit();+ }}+ class="space-y-4"+ >+ <div class="space-y-2">+ <Label for="rule-name">Name</Label>+ <Input+ id="rule-name"+ bind:value={name}+ placeholder="e.g. High Error Rate"+ required+ />+ </div>++ <div class="space-y-2">+ <Label for="rule-channel">Channel</Label>+ <Select.Root type="single" bind:value={channelId}>+ <Select.Trigger class="w-full">+ {channels.find((c) => c.id.toString() === channelId)?.name ||+ 'Select channel'}+ </Select.Trigger>+ <Select.Content>+ {#each channels as ch}+ <Select.Item value={ch.id.toString()}>{ch.name}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>++ <div class="space-y-2">+ <Label for="rule-type">Rule Type</Label>+ <Select.Root type="single" bind:value={ruleType}>+ <Select.Trigger class="w-full">+ {ruleTypeOptions.find((o) => o.value === ruleType)?.label || 'Select type'}+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="new_error">New Issue</Select.Item>+ <Select.Item value="impact_score_critical">Impact Score Critical</Select.Item>+ <Select.Item value="impact_score_high">Impact Score High</Select.Item>+ <Select.Item value="impact_score_medium">Impact Score Medium</Select.Item>+ <!-- <Select.Separator />+ <Select.Item value="error_regression">Error Regression</Select.Item>+ <Select.Item value="error_rate_threshold">Error Rate</Select.Item>+ <Select.Item value="error_count_threshold">Error Count</Select.Item>+ <Select.Item value="endpoint_p95_threshold">Endpoint P95</Select.Item>+ <Select.Item value="endpoint_p99_threshold">Endpoint P99</Select.Item>+ <Select.Item value="endpoint_error_rate">Endpoint Error Rate</Select.Item>+ <Select.Item value="apdex_drop">Apdex Drop</Select.Item>+ <Select.Item value="metric_threshold">Metric Threshold</Select.Item>+ <Select.Item value="no_data">No Data</Select.Item>+ <Select.Item value="task_duration_threshold">Task Duration</Select.Item>+ <Select.Item value="task_failure_rate">Task Failure Rate</Select.Item>+ <Select.Item value="throughput_drop">Throughput Drop</Select.Item> -->+ </Select.Content>+ </Select.Root>+ </div>++ {#if ruleTypeDescriptions[ruleType]}+ <Alert.Root class="bg-amber-50 border-amber-200 text-amber-900 dark:bg-amber-950/50 dark:border-amber-800 dark:text-amber-200 ">+ <TriangleAlert class="text-amber-600 dark:text-amber-400" />+ <Alert.Description class="text-amber-800 dark:text-amber-300">{ruleTypeDescriptions[ruleType]}</Alert.Description>+ </Alert.Root>+ {/if}++ <div class="rounded-md border p-3 space-y-3">+ <p class="text-sm font-medium text-muted-foreground">Rule Configuration</p>++ {#if ruleType === 'error_rate_threshold'}+ <div class="space-y-2">+ <Label for="cfg-threshold">Threshold (%)</Label>+ <Input+ id="cfg-threshold"+ type="number"+ bind:value={thresholdPercent}+ step="0.1"+ min="0"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-lookback">Lookback (minutes)</Label>+ <Input+ id="cfg-lookback"+ type="number"+ bind:value={lookbackMinutes}+ min="1"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-min-req">Min Requests</Label>+ <Input+ id="cfg-min-req"+ type="number"+ bind:value={minRequests}+ min="1"+ />+ </div>+ {:else if ruleType === 'endpoint_p95_threshold' || ruleType === 'endpoint_p99_threshold'}+ <div class="space-y-2">+ <Label for="cfg-endpoint">Endpoint (* for all)</Label>+ <Input id="cfg-endpoint" bind:value={endpoint} placeholder="GET /api/users" />+ </div>+ <div class="space-y-2">+ <Label for="cfg-threshold-ms">Threshold (ms)</Label>+ <Input+ id="cfg-threshold-ms"+ type="number"+ bind:value={thresholdMs}+ min="1"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-lookback-p">Lookback (minutes)</Label>+ <Input+ id="cfg-lookback-p"+ type="number"+ bind:value={lookbackMinutes}+ min="1"+ />+ </div>+ {:else if ruleType === 'apdex_drop'}+ <div class="space-y-2">+ <Label for="cfg-apdex">Apdex Threshold</Label>+ <Input+ id="cfg-apdex"+ type="number"+ bind:value={thresholdApdex}+ step="0.01"+ min="0"+ max="1"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-lookback-a">Lookback (minutes)</Label>+ <Input+ id="cfg-lookback-a"+ type="number"+ bind:value={lookbackMinutes}+ min="1"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-min-req-a">Min Requests</Label>+ <Input+ id="cfg-min-req-a"+ type="number"+ bind:value={minRequests}+ min="1"+ />+ </div>+ {:else if ruleType === 'metric_threshold'}+ <div class="space-y-2">+ <Label for="cfg-metric">Metric Name</Label>+ <Input+ id="cfg-metric"+ bind:value={metricName}+ placeholder="cpu.used_pcnt"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-operator">Operator</Label>+ <Select.Root type="single" bind:value={operator}>+ <Select.Trigger class="w-full">+ {operatorOptions.find((o) => o.value === operator)?.label || operator}+ </Select.Trigger>+ <Select.Content>+ {#each operatorOptions as option}+ <Select.Item value={option.value}>{option.label}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ <div class="space-y-2">+ <Label for="cfg-value">Threshold Value</Label>+ <Input+ id="cfg-value"+ type="number"+ bind:value={thresholdValue}+ step="0.1"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-agg">Aggregation</Label>+ <Select.Root type="single" bind:value={aggregation}>+ <Select.Trigger class="w-full">+ {aggregationOptions.find((o) => o.value === aggregation)?.label ||+ aggregation}+ </Select.Trigger>+ <Select.Content>+ {#each aggregationOptions as option}+ <Select.Item value={option.value}>{option.label}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ <div class="space-y-2">+ <Label for="cfg-lookback-m">Lookback (minutes)</Label>+ <Input+ id="cfg-lookback-m"+ type="number"+ bind:value={lookbackMinutes}+ min="1"+ />+ </div>+ {:else if ruleType === 'no_data'}+ <div class="space-y-2">+ <Label for="cfg-data-type">Data Type</Label>+ <Select.Root type="single" bind:value={dataType}>+ <Select.Trigger class="w-full">+ {dataTypeOptions.find((o) => o.value === dataType)?.label || dataType}+ </Select.Trigger>+ <Select.Content>+ {#each dataTypeOptions as option}+ <Select.Item value={option.value}>{option.label}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ <div class="space-y-2">+ <Label for="cfg-silence">Silence (minutes)</Label>+ <Input+ id="cfg-silence"+ type="number"+ bind:value={silenceMinutes}+ min="1"+ />+ </div>+ {:else if ruleType === 'error_count_threshold'}+ <div class="space-y-2">+ <Label for="cfg-count">Threshold Count</Label>+ <Input+ id="cfg-count"+ type="number"+ bind:value={thresholdCount}+ min="1"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-lookback-ec">Lookback (minutes)</Label>+ <Input+ id="cfg-lookback-ec"+ type="number"+ bind:value={lookbackMinutes}+ min="1"+ />+ </div>+ {:else if ruleType === 'task_duration_threshold'}+ <div class="space-y-2">+ <Label for="cfg-task">Task Name (* for all)</Label>+ <Input id="cfg-task" bind:value={taskName} placeholder="sync_users" />+ </div>+ <div class="space-y-2">+ <Label for="cfg-threshold-ms-t">Threshold (ms)</Label>+ <Input+ id="cfg-threshold-ms-t"+ type="number"+ bind:value={thresholdMs}+ min="1"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-lookback-td">Lookback (minutes)</Label>+ <Input+ id="cfg-lookback-td"+ type="number"+ bind:value={lookbackMinutes}+ min="1"+ />+ </div>+ {:else if ruleType === 'task_failure_rate'}+ <div class="space-y-2">+ <Label for="cfg-task-f">Task Name (* for all)</Label>+ <Input id="cfg-task-f" bind:value={taskName} placeholder="sync_users" />+ </div>+ <div class="space-y-2">+ <Label for="cfg-threshold-pct">Threshold (%)</Label>+ <Input+ id="cfg-threshold-pct"+ type="number"+ bind:value={thresholdPercent}+ step="0.1"+ min="0"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-lookback-tf">Lookback (minutes)</Label>+ <Input+ id="cfg-lookback-tf"+ type="number"+ bind:value={lookbackMinutes}+ min="1"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-min-exec">Min Executions</Label>+ <Input+ id="cfg-min-exec"+ type="number"+ bind:value={minExecutions}+ min="1"+ />+ </div>+ {:else if ruleType === 'throughput_drop'}+ <div class="space-y-2">+ <Label for="cfg-drop">Drop (%)</Label>+ <Input+ id="cfg-drop"+ type="number"+ bind:value={dropPercent}+ step="0.1"+ min="0"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-lookback-tp">Lookback (minutes)</Label>+ <Input+ id="cfg-lookback-tp"+ type="number"+ bind:value={lookbackMinutes}+ min="1"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-baseline">Baseline Window (minutes)</Label>+ <Input+ id="cfg-baseline"+ type="number"+ bind:value={baselineWindowMinutes}+ min="1"+ />+ </div>+ {:else if ruleType === 'endpoint_error_rate'}+ <div class="space-y-2">+ <Label for="cfg-endpoint-er">Endpoint</Label>+ <Input+ id="cfg-endpoint-er"+ bind:value={endpoint}+ placeholder="POST /api/checkout"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-threshold-er">Threshold (%)</Label>+ <Input+ id="cfg-threshold-er"+ type="number"+ bind:value={thresholdPercent}+ step="0.1"+ min="0"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-lookback-er">Lookback (minutes)</Label>+ <Input+ id="cfg-lookback-er"+ type="number"+ bind:value={lookbackMinutes}+ min="1"+ />+ </div>+ <div class="space-y-2">+ <Label for="cfg-min-req-er">Min Requests</Label>+ <Input+ id="cfg-min-req-er"+ type="number"+ bind:value={minRequests}+ min="1"+ />+ </div>+ {:else if ruleType === 'new_error'}+ <div class="space-y-2">+ <Label for="cfg-ignore">Ignore Patterns (optional, comma-separated)</Label>+ <Input+ id="cfg-ignore"+ bind:value={ignorePatterns}+ placeholder="*timeout*, *context canceled*"+ />+ </div>+ {:else if ruleType === 'error_regression'}+ <div class="flex items-center gap-2">+ <input+ id="cfg-include-archived"+ type="checkbox"+ bind:checked={includeArchived}+ class="h-4 w-4 rounded border-border"+ />+ <Label for="cfg-include-archived">Include archived exceptions</Label>+ </div>+ {:else if ruleType === 'impact_score_critical' || ruleType === 'impact_score_high' || ruleType === 'impact_score_medium'}+ <div class="space-y-2">+ <Label for="cfg-min-req-impact">Min Requests</Label>+ <Input+ id="cfg-min-req-impact"+ type="number"+ bind:value={minRequests}+ min="1"+ />+ </div>+ {/if}+ </div>++ <div class="space-y-2">+ <Label for="rule-cooldown">Cooldown (minutes)</Label>+ <Input+ id="rule-cooldown"+ type="number"+ bind:value={cooldownMinutes}+ min="1"+ />+ </div>++ {#if error}+ <p class="text-sm text-destructive">{error}</p>+ {/if}+ </form>++ <AlertDialog.Footer>+ <AlertDialog.Cancel disabled={loading}>Cancel</AlertDialog.Cancel>+ <Button onclick={handleSubmit} disabled={loading}>+ {#if isEditing}+ <Check class="mr-2 h-4 w-4" />+ {#if loading}+ Updating...+ {:else}+ Update Rule+ {/if}+ {:else}+ <Plus class="mr-2 h-4 w-4" />+ {#if loading}+ Creating...+ {:else}+ New Rule+ {/if}+ {/if}+ </Button>+ </AlertDialog.Footer>+ </AlertDialog.Content>+</AlertDialog.Root>diff --git a/frontend/src/routes/notifications/snooze-dialog.svelte b/frontend/src/routes/notifications/snooze-dialog.sveltenew file mode 100644index 00000000..e66e3518--- /dev/null+++ b/frontend/src/routes/notifications/snooze-dialog.svelte@@ -0,0 +1,105 @@+<script lang="ts">+ import * as AlertDialog from '$lib/components/ui/alert-dialog';+ import { Button } from '$lib/components/ui/button';+ import { Clock } from '@lucide/svelte';+ import { toast } from 'svelte-sonner';+ import { api } from '$lib/api';+ import { projectsState } from '$lib/state/projects.svelte';++ interface Props {+ open: boolean;+ ruleId: number | null;+ onSaved: () => void;+ }++ let { open = $bindable(), ruleId, onSaved }: Props = $props();++ let loading = $state(false);++ const presets = [+ { label: '30 minutes', minutes: 30 },+ { label: '1 hour', minutes: 60 },+ { label: '4 hours', minutes: 240 },+ { label: '8 hours', minutes: 480 },+ { label: '24 hours', minutes: 1440 }+ ];++ async function snooze(durationMinutes: number) {+ if (!ruleId) return;+ loading = true;++ try {+ await api.post(+ `/notification-rules/${ruleId}/snooze`,+ { durationMinutes },+ { projectId: projectsState.currentProjectId ?? undefined }+ );+ toast.success('Rule snoozed', { position: 'top-center' });+ onSaved();+ } catch {+ toast.error('Failed to snooze rule', { position: 'top-center' });+ } finally {+ loading = false;+ }+ }++ async function clearSnooze() {+ if (!ruleId) return;+ loading = true;++ try {+ await api.post(+ `/notification-rules/${ruleId}/snooze`,+ { durationMinutes: 0 },+ { projectId: projectsState.currentProjectId ?? undefined }+ );+ toast.success('Snooze cleared', { position: 'top-center' });+ onSaved();+ } catch {+ toast.error('Failed to clear snooze', { position: 'top-center' });+ } finally {+ loading = false;+ }+ }++ function handleOpenChange(isOpen: boolean) {+ open = isOpen;+ }+</script>++<AlertDialog.Root {open} onOpenChange={handleOpenChange}>+ <AlertDialog.Content class="max-w-sm">+ <AlertDialog.Header>+ <AlertDialog.Title>Snooze Rule</AlertDialog.Title>+ <AlertDialog.Description>+ Temporarily silence this rule for a set duration+ </AlertDialog.Description>+ </AlertDialog.Header>++ <div class="grid gap-2">+ {#each presets as preset}+ <Button+ variant="outline"+ class="w-full justify-start"+ disabled={loading}+ onclick={() => snooze(preset.minutes)}+ >+ <Clock class="mr-2 h-4 w-4" />+ {preset.label}+ </Button>+ {/each}+ <Button+ variant="ghost"+ class="w-full justify-start text-muted-foreground"+ disabled={loading}+ onclick={clearSnooze}+ >+ Clear snooze+ </Button>+ </div>++ <AlertDialog.Footer>+ <AlertDialog.Cancel disabled={loading}>Cancel</AlertDialog.Cancel>+ </AlertDialog.Footer>+ </AlertDialog.Content>+</AlertDialog.Root>