Skip to content

The only tool you need to know what is happening and how to fix it.

feat: better back button + tooltip update + impact calculation update + slow endpoints

ddux5b4378d6a2dc
diff --git a/backend/app/controllers/endpoint.controller.go b/backend/app/controllers/endpoint.controller.go
index bdf6de89..3650cb47 100644
--- a/backend/app/controllers/endpoint.controller.go
+++ b/backend/app/controllers/endpoint.controller.go
@@ -4,6 +4,8 @@ import (
"backend/app/middleware"
"backend/app/models"
"backend/app/repositories"
+ "database/sql"
+ "errors"
"net/http"
"net/url"
"time"
@@ -196,4 +198,62 @@ func (e endpointController) GetStackedChart(c *gin.Context) {
c.JSON(http.StatusOK, data)
}
+func (e endpointController) GetSlowEndpoint(c *gin.Context) {
+ projectId, err := middleware.GetProjectId(c)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))
+ return
+ }
+
+ rawEndpoint := c.Query("endpoint")
+ if rawEndpoint == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "endpoint is required"})
+ return
+ }
+
+ endpoint, err := url.PathUnescape(rawEndpoint)
+ if err != nil {
+ endpoint = rawEndpoint
+ }
+
+ offsetMs, reason, err := repositories.EndpointRepository.GetSlowEndpoint(c, projectId, endpoint)
+ if errors.Is(err, sql.ErrNoRows) {
+ c.JSON(http.StatusOK, gin.H{"offsetMs": 0, "reason": ""})
+ return
+ }
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading slow endpoint: %w", err))
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{"offsetMs": offsetMs, "reason": reason})
+}
+
+type SetSlowEndpointRequest struct {
+ Endpoint string `json:"endpoint" binding:"required"`
+ OffsetMs uint32 `json:"offsetMs"`
+ Reason string `json:"reason"`
+}
+
+func (e endpointController) SetSlowEndpoint(c *gin.Context) {
+ projectId, err := middleware.GetProjectId(c)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))
+ return
+ }
+
+ var request SetSlowEndpointRequest
+ if err := c.ShouldBindJSON(&request); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+
+ if err := repositories.EndpointRepository.UpsertSlowEndpoint(c, projectId, request.Endpoint, request.OffsetMs, request.Reason); err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error saving slow endpoint: %w", err))
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{"offsetMs": request.OffsetMs})
+}
+
var EndpointController = endpointController{}
diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.go
index 60c24703..bfceaf5d 100644
--- a/backend/app/controllers/routes.go
+++ b/backend/app/controllers/routes.go
@@ -50,6 +50,8 @@ func RegisterControllers(router *gin.RouterGroup) {
router.POST("/endpoints/grouped", middleware.UseAppAuth, middleware.RequireProjectAccess, EndpointController.FindGroupedByEndpoint)
router.POST("/endpoints/endpoint", middleware.UseAppAuth, middleware.RequireProjectAccess, EndpointController.FindByEndpoint)
router.POST("/endpoints/chart", middleware.UseAppAuth, middleware.RequireProjectAccess, EndpointController.GetStackedChart)
+ router.GET("/endpoints/slow", middleware.UseAppAuth, middleware.RequireProjectAccess, EndpointController.GetSlowEndpoint)
+ router.POST("/endpoints/slow", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, EndpointController.SetSlowEndpoint)
router.POST("/endpoints/:endpointId", middleware.UseAppAuth, middleware.RequireProjectAccess, EndpointDetailController.GetEndpointDetail)
// Tasks (projectId in body)
diff --git a/backend/app/migrations/ch/0023_create_slow_endpoints.up.sql b/backend/app/migrations/ch/0023_create_slow_endpoints.up.sql
new file mode 100644
index 00000000..d7a5e59f
--- /dev/null
+++ b/backend/app/migrations/ch/0023_create_slow_endpoints.up.sql
@@ -0,0 +1,9 @@
+CREATE TABLE IF NOT EXISTS slow_endpoints
+(
+ `project_id` UUID,
+ `endpoint` LowCardinality(String),
+ `offset_ms` UInt32 DEFAULT 0,
+ `reason` String DEFAULT ''
+)
+ENGINE = ReplacingMergeTree()
+ORDER BY (project_id, endpoint)
diff --git a/backend/app/models/endpoint.model.go b/backend/app/models/endpoint.model.go
index 09add3ca..e638fe27 100644
--- a/backend/app/models/endpoint.model.go
+++ b/backend/app/models/endpoint.model.go
@@ -29,7 +29,8 @@ type EndpointStats struct {
P99Duration time.Duration `json:"p99Duration"`
AvgDuration time.Duration `json:"avgDuration"`
LastSeen time.Time `json:"lastSeen"`
- Impact float64 `json:"impact"` // 0-1 Apdex-based impact score
+ Impact float64 `json:"impact"` // 0-1 impact score
+ ImpactReason string `json:"impactReason"` // human-readable explanation of the dominant impact factor
}
// EndpointDetailStats contains detailed statistics for a specific endpoint
diff --git a/backend/app/repositories/endpoint.repository.go b/backend/app/repositories/endpoint.repository.go
index 8f81f871..a230792e 100644
--- a/backend/app/repositories/endpoint.repository.go
+++ b/backend/app/repositories/endpoint.repository.go
@@ -87,11 +87,14 @@ func (e *endpointRepository) FindAll(ctx context.Context, projectId uuid.UUID, f
func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string) ([]models.EndpointStats, int64, error) {
// Build WHERE clause with optional search filter
+ // Count query uses bare column names; main query uses e. prefix for LEFT JOIN
whereClause := "project_id = ? AND recorded_at >= ? AND recorded_at <= ?"
+ joinWhereClause := "e.project_id = ? AND e.recorded_at >= ? AND e.recorded_at <= ?"
args := []interface{}{projectId, fromDate, toDate}
if search != "" {
whereClause += " AND positionCaseInsensitive(endpoint, ?) > 0"
+ joinWhereClause += " AND positionCaseInsensitive(e.endpoint, ?) > 0"
args = append(args, search)
}
@@ -127,37 +130,65 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectI
sortDir = "ASC"
}
- // Apdex thresholds: Good <= 750ms, Tolerable <= 1500ms, Bad > 1500ms or error
- // Duration is in nanoseconds: 750ms = 750,000,000ns, 1500ms = 1,500,000,000ns
query := `SELECT
- endpoint,
- count() as count,
- quantile(0.5)(duration) as p50_duration,
- quantile(0.95)(duration) as p95_duration,
- quantile(0.99)(duration) as p99_duration,
- avg(duration) as avg_duration,
- max(recorded_at) as last_seen,
+ endpoint, total_count as count, p50_duration, p95_duration, p99_duration,
+ avg_duration, last_seen, offset_ms,
+ satisfied_count, tolerating_count, bad_count, client_error_count,
greatest(
- -- Base score: 1 - apdex
- if(count() > 0,
- 1.0 - (
- (countIf(duration <= 750000000 AND status_code < 500) +
- countIf(duration > 750000000 AND duration <= 1500000000 AND status_code < 500) * 0.5)
- / count()
- ),
- 0.0
- ),
- -- Floor based on bad percentage
+ 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(
- countIf(duration > 1500000000 OR status_code >= 500) / count() > 0.33, 0.75,
- countIf(duration > 1500000000 OR status_code >= 500) / count() > 0.20, 0.50,
- countIf(duration > 1500000000 OR status_code >= 500) / count() > 0.10, 0.25,
- 0.0
- )
+ 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(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 endpoints
- WHERE ` + whereClause + `
- GROUP BY endpoint
+ FROM (
+ SELECT
+ endpoint,
+ offset_ms,
+ count() as total_count,
+ quantile(0.5)(duration) as p50_duration,
+ quantile(0.95)(duration) as p95_duration,
+ quantile(0.99)(duration) as p99_duration,
+ avg(duration) as avg_duration,
+ max(recorded_at) as last_seen,
+ 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 ` + joinWhereClause + `
+ )
+ GROUP BY endpoint, offset_ms
+ )
ORDER BY ` + orderExpr + ` ` + sortDir + `
LIMIT ? OFFSET ?`
@@ -174,13 +205,18 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectI
for rows.Next() {
var s models.EndpointStats
var p50, p95, p99, avg float64
- if err := rows.Scan(&s.Endpoint, &s.Count, &p50, &p95, &p99, &avg, &s.LastSeen, &s.Impact); err != nil {
+ var offsetMs uint32
+ var satisfiedCount, toleratingCount, badCount, clientErrorCount uint64
+ if err := rows.Scan(&s.Endpoint, &s.Count, &p50, &p95, &p99, &avg, &s.LastSeen,
+ &offsetMs, &satisfiedCount, &toleratingCount, &badCount, &clientErrorCount,
+ &s.Impact); err != nil {
return nil, 0, err
}
s.P50Duration = time.Duration(p50)
s.P95Duration = time.Duration(p95)
s.P99Duration = time.Duration(p99)
s.AvgDuration = time.Duration(avg)
+ s.ImpactReason = computeImpactReason(s.Count, satisfiedCount, toleratingCount, badCount, clientErrorCount, p99, offsetMs)
stats = append(stats, s)
}
@@ -436,39 +472,66 @@ func (e *endpointRepository) ErrorRateByInterval(ctx context.Context, projectId
return points, nil
}
-// FindWorstEndpoints returns endpoints ordered by Apdex-based impact score
-// Higher score = worse performance (1 - apdex with floor based on bad request percentage)
func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId uuid.UUID, start, end time.Time, limit int) ([]models.EndpointStats, error) {
- // Apdex thresholds: Good <= 750ms, Tolerable <= 1500ms, Bad > 1500ms or error
- // Duration is in nanoseconds: 750ms = 750,000,000ns, 1500ms = 1,500,000,000ns
query := `SELECT
- endpoint,
- count() as count,
- quantile(0.5)(duration) as p50_duration,
- quantile(0.95)(duration) as p95_duration,
- avg(duration) as avg_duration,
- max(recorded_at) as last_seen,
+ endpoint, total_count, p50_duration, p95_duration, p99_duration,
+ avg_duration, last_seen, offset_ms,
+ satisfied_count, tolerating_count, bad_count, client_error_count,
greatest(
- -- Base score: 1 - apdex
- if(count() > 0,
- 1.0 - (
- (countIf(duration <= 750000000 AND status_code < 500) +
- countIf(duration > 750000000 AND duration <= 1500000000 AND status_code < 500) * 0.5)
- / count()
- ),
- 0.0
- ),
- -- Floor based on bad percentage
+ 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(
- countIf(duration > 1500000000 OR status_code >= 500) / count() > 0.33, 0.75,
- countIf(duration > 1500000000 OR status_code >= 500) / count() > 0.20, 0.50,
- countIf(duration > 1500000000 OR status_code >= 500) / count() > 0.10, 0.25,
- 0.0
- )
+ 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(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 endpoints
- WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
- GROUP BY endpoint
+ FROM (
+ SELECT
+ endpoint,
+ offset_ms,
+ count() as total_count,
+ quantile(0.5)(duration) as p50_duration,
+ quantile(0.95)(duration) as p95_duration,
+ quantile(0.99)(duration) as p99_duration,
+ avg(duration) as avg_duration,
+ max(recorded_at) as last_seen,
+ 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
+ )
ORDER BY impact DESC
LIMIT ?`
@@ -481,13 +544,19 @@ func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId u
var stats []models.EndpointStats
for rows.Next() {
var s models.EndpointStats
- var p50, p95, avg float64
- if err := rows.Scan(&s.Endpoint, &s.Count, &p50, &p95, &avg, &s.LastSeen, &s.Impact); err != nil {
+ var p50, p95, p99, avg float64
+ var offsetMs uint32
+ var satisfiedCount, toleratingCount, badCount, clientErrorCount uint64
+ if err := rows.Scan(&s.Endpoint, &s.Count, &p50, &p95, &p99, &avg, &s.LastSeen,
+ &offsetMs, &satisfiedCount, &toleratingCount, &badCount, &clientErrorCount,
+ &s.Impact); err != nil {
return nil, err
}
s.P50Duration = time.Duration(p50)
s.P95Duration = time.Duration(p95)
+ s.P99Duration = time.Duration(p99)
s.AvgDuration = time.Duration(avg)
+ s.ImpactReason = computeImpactReason(s.Count, satisfiedCount, toleratingCount, badCount, clientErrorCount, p99, offsetMs)
stats = append(stats, s)
}
@@ -674,4 +743,26 @@ func (e *endpointRepository) GetEndpointStackedChart(ctx context.Context, projec
}, nil
}
+func (e *endpointRepository) GetSlowEndpoint(ctx context.Context, projectId uuid.UUID, endpoint string) (uint32, string, error) {
+ var offsetMs uint32
+ var reason string
+ err := (*chdb.Conn).QueryRow(ctx, "SELECT offset_ms, reason FROM slow_endpoints FINAL WHERE project_id = ? AND endpoint = ?", projectId, endpoint).Scan(&offsetMs, &reason)
+ return offsetMs, reason, err
+}
+
+func (e *endpointRepository) UpsertSlowEndpoint(ctx context.Context, projectId uuid.UUID, endpoint string, offsetMs uint32, reason string) error {
+ err := (*chdb.Conn).Exec(ctx, "ALTER TABLE slow_endpoints DELETE WHERE project_id = ? AND endpoint = ?", projectId, endpoint)
+ if err != nil {
+ return err
+ }
+ batch, err := (*chdb.Conn).PrepareBatch(ctx, "INSERT INTO slow_endpoints (project_id, endpoint, offset_ms, reason)")
+ if err != nil {
+ return err
+ }
+ if err := batch.Append(projectId, endpoint, offsetMs, reason); err != nil {
+ return err
+ }
+ return batch.Send()
+}
+
var EndpointRepository = endpointRepository{}
diff --git a/backend/app/repositories/impact.go b/backend/app/repositories/impact.go
new file mode 100644
index 00000000..2ab6ae95
--- /dev/null
+++ b/backend/app/repositories/impact.go
@@ -0,0 +1,139 @@
+package repositories
+
+import (
+ "fmt"
+ "math"
+ "time"
+)
+
+func computeImpactReason(
+ total, satisfiedCount, toleratingCount, badCount, clientErrorCount uint64,
+ p99Ns float64,
+ offsetMs uint32,
+) string {
+ if total == 0 {
+ return "Endpoint is healthy"
+ }
+
+ totalF := float64(total)
+ badF := float64(badCount)
+ clientF := float64(clientErrorCount)
+ offsetNs := float64(offsetMs) * 1_000_000
+
+ // 1. Inverted Apdex
+ apdexScore := 1.0 - (float64(satisfiedCount)+float64(toleratingCount)*0.5)/totalF
+
+ // 2. Error Rate Floor
+ badRate := badF / totalF
+ var errorRateScore float64
+ switch {
+ case badRate > 0.33:
+ errorRateScore = 0.75
+ case badRate > 0.20:
+ errorRateScore = 0.50
+ case badRate > 0.10:
+ errorRateScore = 0.25
+ }
+
+ // 3. P99 Floor (offset-adjusted)
+ adjustedP99 := p99Ns - offsetNs
+ var p99Score float64
+ switch {
+ case adjustedP99 > 8_000_000_000:
+ p99Score = 0.75
+ case adjustedP99 > 6_000_000_000:
+ p99Score = 0.50
+ case adjustedP99 > 3_000_000_000:
+ p99Score = 0.25
+ }
+
+ // 4. Client Error Floor (only when count > 10)
+ var clientErrorScore float64
+ if total > 10 {
+ clientRate := clientF / totalF
+ switch {
+ case clientRate > 0.50:
+ clientErrorScore = 0.75
+ case clientRate > 0.25:
+ clientErrorScore = 0.50
+ }
+ }
+
+ // 5. Volume-Aware Error Floor
+ var volumeScore float64
+ switch {
+ case badRate > 0.10 && badCount >= 500:
+ volumeScore = 0.75
+ case badRate > 0.10 && badCount >= 50:
+ volumeScore = 0.50
+ case badRate > 0.05 && badCount >= 2000:
+ volumeScore = 0.75
+ case badRate > 0.05 && badCount >= 500:
+ volumeScore = 0.50
+ case badRate > 0.05 && badCount >= 50:
+ volumeScore = 0.25
+ case badRate > 0.01 && badCount >= 10000:
+ volumeScore = 0.75
+ case badRate > 0.01 && badCount >= 2000:
+ volumeScore = 0.50
+ case badRate > 0.01 && badCount >= 500:
+ volumeScore = 0.25
+ }
+
+ maxScore := math.Max(apdexScore, math.Max(errorRateScore, math.Max(p99Score, math.Max(clientErrorScore, volumeScore))))
+
+ if maxScore < 0.25 {
+ return "Endpoint is healthy"
+ }
+
+ // Priority when tied: P99 > Volume > Client Error > Error Rate > Apdex
+ switch {
+ case p99Score >= maxScore:
+ p99Duration := time.Duration(p99Ns)
+ return fmt.Sprintf("P99 latency is %s", formatDurationHuman(p99Duration))
+ case volumeScore >= maxScore:
+ return fmt.Sprintf("%s errors with %.1f%% error rate", formatCount(badCount), badRate*100)
+ case clientErrorScore >= maxScore:
+ return fmt.Sprintf("%.0f%% of requests returning 4xx errors", clientF/totalF*100)
+ case errorRateScore >= maxScore:
+ return fmt.Sprintf("%.0f%% of requests are slow or failing", badRate*100)
+ default:
+ return fmt.Sprintf("%.0f%% of requests are slow or failing", (1-float64(satisfiedCount)/totalF)*100)
+ }
+}
+
+func formatDurationHuman(d time.Duration) string {
+ if d >= time.Second {
+ secs := d.Seconds()
+ if secs >= 10 {
+ return fmt.Sprintf("%.0fs", secs)
+ }
+ return fmt.Sprintf("%.1fs", secs)
+ }
+ return fmt.Sprintf("%.0fms", float64(d)/float64(time.Millisecond))
+}
+
+func formatCount(n uint64) string {
+ if n >= 1_000_000 {
+ return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
+ }
+ if n >= 1_000 {
+ return fmt.Sprintf("%s", addCommas(n))
+ }
+ return fmt.Sprintf("%d", n)
+}
+
+func addCommas(n uint64) string {
+ s := fmt.Sprintf("%d", n)
+ if len(s) <= 3 {
+ return s
+ }
+ var result []byte
+ for i, c := range s {
+ if i > 0 && (len(s)-i)%3 == 0 {
+ result = append(result, ',')
+ }
+ result = append(result, byte(c))
+ }
+ return string(result)
+}
diff --git a/frontend/src/lib/components/ui/impact-badge/impact-badge.svelte b/frontend/src/lib/components/ui/impact-badge/impact-badge.svelte
index fae24281..412b925b 100644
--- a/frontend/src/lib/components/ui/impact-badge/impact-badge.svelte
+++ b/frontend/src/lib/components/ui/impact-badge/impact-badge.svelte
@@ -1,20 +1,21 @@
<script lang="ts">
import { TriangleAlert, CheckCircle } from 'lucide-svelte';
+ import * as Tooltip from '$lib/components/ui/tooltip';
let {
score,
- showIcon
+ showIcon,
+ reason
}: {
- score: number; // 0-1 Apdex-based impact score
+ score: number; // 0-1 impact score
showIcon?: boolean;
+ reason?: string;
} = $props();
// Map score to impact level
type ImpactLevel = 'critical' | 'high' | 'medium' | 'good';
const level = $derived<ImpactLevel>(
- score >= 0.75 ? 'critical' :
- score >= 0.50 ? 'high' :
- score >= 0.25 ? 'medium' : 'good'
+ score >= 0.75 ? 'critical' : score >= 0.5 ? 'high' : score >= 0.25 ? 'medium' : 'good'
);
// Default showIcon to true for critical and high levels
@@ -54,7 +55,7 @@
});
</script>
-{#if config()}
+{#snippet badge()}
<span
class="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium {config()
?.bg} {config()?.text}"
@@ -68,4 +69,19 @@
{/if}
{config()?.label}
</span>
+{/snippet}
+
+{#if config()}
+ {#if reason}
+ <Tooltip.Root>
+ <Tooltip.Trigger class="cursor-default">
+ {@render badge()}
+ </Tooltip.Trigger>
+ <Tooltip.Content side="left">
+ {reason}
+ </Tooltip.Content>
+ </Tooltip.Root>
+ {:else}
+ {@render badge()}
+ {/if}
{/if}
diff --git a/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte b/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte
index ef046969..863f4961 100644
--- a/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte
+++ b/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte
@@ -1,15 +1,15 @@
<script lang="ts">
- import { Tooltip as TooltipPrimitive } from "bits-ui";
- import { cn } from "$lib/utils.js";
- import TooltipPortal from "./tooltip-portal.svelte";
- import type { ComponentProps } from "svelte";
- import type { WithoutChildrenOrChild } from "$lib/utils.js";
+ import { Tooltip as TooltipPrimitive } from 'bits-ui';
+ import { cn } from '$lib/utils.js';
+ import TooltipPortal from './tooltip-portal.svelte';
+ import type { ComponentProps } from 'svelte';
+ import type { WithoutChildrenOrChild } from '$lib/utils.js';
let {
ref = $bindable(null),
class: className,
sideOffset = 0,
- side = "top",
+ side = 'top',
children,
arrowClasses,
portalProps,
@@ -27,7 +27,7 @@
{sideOffset}
{side}
class={cn(
- "bg-white text-foreground shadow-[0_2px_16px_rgba(0,0,0,0.25)] dark:bg-foreground dark:text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-w-[220px] origin-(--bits-tooltip-content-transform-origin) rounded-sm px-3 py-2 text-xs",
+ 'z-50 max-w-[220px] origin-(--bits-tooltip-content-transform-origin) animate-in rounded-sm border bg-white px-3 py-2 text-xs text-foreground shadow-[none] fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 dark:bg-foreground dark:text-background',
className
)}
{...restProps}
@@ -37,11 +37,15 @@
{#snippet child({ props })}
<div
class={cn(
- "bg-white dark:bg-foreground z-50 size-2.5 rotate-45 rounded-[2px]",
- "data-[side=top]:translate-x-1/2 data-[side=top]:translate-y-[calc(-50%_+_2px)]",
- "data-[side=bottom]:-translate-x-1/2 data-[side=bottom]:-translate-y-[calc(-50%_+_1px)]",
- "data-[side=right]:translate-x-[calc(50%_+_2px)] data-[side=right]:translate-y-1/2",
- "data-[side=left]:-translate-y-[calc(50%_-_3px)]",
+ 'z-50 size-2.5 rotate-45 border-border bg-white dark:bg-foreground',
+ 'data-[side=top]:border-r data-[side=top]:border-b',
+ 'data-[side=bottom]:border-t data-[side=bottom]:border-l',
+ 'data-[side=left]:border-r data-[side=left]:border-b',
+ 'data-[side=right]:border-t data-[side=right]:border-l',
+ 'data-[side=top]:translate-x-1/2 data-[side=top]:translate-y-[calc(-50%_+_3px)]',
+ 'data-[side=bottom]:-translate-x-1/2 data-[side=bottom]:-translate-y-[calc(-50%_+_1px)]',
+ 'data-[side=right]:translate-x-[calc(50%_+_2px)] data-[side=right]:translate-y-1/2',
+ 'data-[side=left]:-translate-y-[calc(50%_-_3px)]',
arrowClasses
)}
{...props}
diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelte
index 65ae0650..50756602 100644
--- a/frontend/src/routes/+page.svelte
+++ b/frontend/src/routes/+page.svelte
@@ -74,7 +74,8 @@
p95Duration: number;
avgDuration: number;
lastSeen: string;
- impact: number; // 0-1 Apdex-based impact score from backend
+ impact: number;
+ impactReason: string;
};
type DashboardOverview = {
@@ -488,7 +489,7 @@
{formatDuration(endpoint.p95Duration)}
</Table.Cell>
<Table.Cell class="py-3 text-right">
- <ImpactBadge score={endpoint.impact} />
+ <ImpactBadge score={endpoint.impact} reason={endpoint.impactReason} />
</Table.Cell>
</Table.Row>
{/each}
diff --git a/frontend/src/routes/endpoints/+page.svelte b/frontend/src/routes/endpoints/+page.svelte
index cd77683b..b6c2fd78 100644
--- a/frontend/src/routes/endpoints/+page.svelte
+++ b/frontend/src/routes/endpoints/+page.svelte
@@ -50,7 +50,8 @@
p99Duration: number;
avgDuration: number;
lastSeen: string;
- impact: number; // 0-1 Apdex-based impact score from backend
+ impact: number;
+ impactReason: string;
};
type SortField = 'count' | 'p50_duration' | 'p95_duration' | 'p99_duration' | 'last_seen' | 'impact';
@@ -517,7 +518,7 @@
/>
<TracewayTableHeader
label="Impact"
- tooltip="Priority based on traffic × response time variance"
+ tooltip="Impact score based on Apdex, error rates, P99 latency, and request volume"
sortField="impact"
currentSortField={orderBy}
{sortDirection}
@@ -549,7 +550,7 @@
{formatDuration(endpoint.p99Duration)}
</Table.Cell>
<Table.Cell class="text-right">
- <ImpactBadge score={endpoint.impact} />
+ <ImpactBadge score={endpoint.impact} reason={endpoint.impactReason} />
</Table.Cell>
</Table.Row>
{/each}
diff --git a/frontend/src/routes/endpoints/[endpoint]/+page.svelte b/frontend/src/routes/endpoints/[endpoint]/+page.svelte
index 96ab2343..6ca6964c 100644
--- a/frontend/src/routes/endpoints/[endpoint]/+page.svelte
+++ b/frontend/src/routes/endpoints/[endpoint]/+page.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import { onMount } from 'svelte';
+ import { onMount, onDestroy } from 'svelte';
import { api } from '$lib/api';
import {
formatDuration,
@@ -15,7 +15,7 @@
import { Button } from '$lib/components/ui/button';
import { LoadingCircle } from '$lib/components/ui/loading-circle';
import { TimeRangePicker } from '$lib/components/ui/time-range-picker';
- import { ArrowLeft } from '@lucide/svelte';
+ import { ArrowLeft, Snail } from '@lucide/svelte';
import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';
import { TableEmptyState } from '$lib/components/ui/table-empty-state';
import { CalendarDate } from '@internationalized/date';
@@ -23,13 +23,18 @@
import { projectsState } from '$lib/state/projects.svelte';
import AttributesDisplay from '$lib/components/attributes-display.svelte';
import { createRowClickHandler } from '$lib/utils/navigation';
- import { createSmartBackHandler } from '$lib/utils/back-navigation';
+ import { goto } from '$app/navigation';
import PaginationFooter from '$lib/components/ui/pagination-footer/pagination-footer.svelte';
import PageHeader from '$lib/components/issues/page-header.svelte';
+ import { Input } from '$lib/components/ui/input';
+ import * as AlertDialog from '$lib/components/ui/alert-dialog';
+ import { toast } from 'svelte-sonner';
import { resolve } from '$app/paths';
import {
presetMinutes,
getTimeRangeFromPreset,
+ parseTimeRangeFromUrl,
+ getResolvedTimeRange,
dateToCalendarDate,
dateToTimeString,
updateUrl
@@ -130,6 +135,14 @@
let orderBy = $state<SortField>(initialSort.field as SortField);
let sortDirection = $state<SortDirection>(initialSort.direction);
+ // Slow endpoint state
+ let offsetMs = $state<number>(0);
+ let reason = $state('');
+ let showSlowDialog = $state(false);
+ let slowLoading = $state(false);
+ let offsetInput = $state('');
+ let reasonInput = $state('');
+
// Combine date and time into UTC ISO datetime string
function getFromDateTimeUTC(): string {
const [hour, minute] = (fromTime || '00:00').split(':').map(Number);
@@ -149,6 +162,22 @@
return toUTCISO(dt);
}
+ function goBackToEndpoints(event: MouseEvent) {
+ const params = new URLSearchParams();
+ if (selectedPreset) {
+ params.set('preset', selectedPreset);
+ } else {
+ params.set('from', getFromDateTimeUTC());
+ params.set('to', getToDateTimeUTC());
+ }
+ const href = resolve('/endpoints') + '?' + params.toString();
+ if (event.ctrlKey || event.metaKey) {
+ window.open(href, '_blank');
+ } else {
+ goto(href);
+ }
+ }
+
function handleTimeRangeChange(
from: { date: CalendarDate; time: string },
to: { date: CalendarDate; time: string },
@@ -238,8 +267,62 @@
loadData(false);
}
+ async function loadSlowEndpoint() {
+ try {
+ const response = await api.get(
+ `/endpoints/slow?endpoint=${encodeURIComponent(data.endpoint)}`,
+ { projectId: projectsState.currentProjectId ?? undefined }
+ );
+ offsetMs = response.offsetMs ?? 0;
+ reason = response.reason ?? '';
+ } catch {
+ offsetMs = 0;
+ reason = '';
+ }
+ }
+
+ async function saveSlowEndpoint() {
+ slowLoading = true;
+ try {
+ const value = parseInt(offsetInput) || 0;
+ await api.post(
+ '/endpoints/slow',
+ { endpoint: decodeURIComponent(data.endpoint), offsetMs: Math.max(0, value), reason: reasonInput },
+ { projectId: projectsState.currentProjectId ?? undefined }
+ );
+ offsetMs = Math.max(0, value);
+ reason = reasonInput;
+ showSlowDialog = false;
+ toast.success('Expected performance updated');
+ } catch (e: any) {
+ toast.error(e.message || 'Failed to save');
+ } finally {
+ slowLoading = false;
+ }
+ }
+
+ function handlePopState() {
+ const urlParams = parseTimeRangeFromUrl(timezone);
+ const range = getResolvedTimeRange(urlParams, timezone);
+ selectedPreset = urlParams.preset;
+ fromDate = dateToCalendarDate(range.from, timezone);
+ toDate = dateToCalendarDate(range.to, timezone);
+ fromTime = dateToTimeString(range.from, timezone);
+ toTime = dateToTimeString(range.to, timezone);
+ page = 1;
+ loadData(false);
+ }
+
onMount(() => {
+ window.addEventListener('popstate', handlePopState);
loadData(false);
+ loadSlowEndpoint();
+ });
+
+ onDestroy(() => {
+ if (typeof window !== 'undefined') {
+ window.removeEventListener('popstate', handlePopState);
+ }
});
</script>
@@ -249,7 +332,7 @@
status={404}
title="Endpoint Not Found"
description="The endpoint you're looking for doesn't exist or has no recorded traces."
- onBack={createSmartBackHandler({ fallbackPath: resolve('/endpoints') })}
+ onBack={goBackToEndpoints}
backLabel="Back to Endpoints"
onRetry={() => loadData(false)}
identifier={decodeURIComponent(data.endpoint)}
@@ -259,7 +342,7 @@
status={errorStatus === 400 ? 400 : errorStatus === 422 ? 422 : 400}
title="Failed to Load Traces"
description={error}
- onBack={createSmartBackHandler({ fallbackPath: resolve('/endpoints') })}
+ onBack={goBackToEndpoints}
backLabel="Back to Endpoints"
onRetry={() => loadData(false)}
/>
@@ -269,10 +352,14 @@
<PageHeader
title={decodeURIComponent(data.endpoint)}
subtitle="Trace instances for this endpoint"
- onBack={createSmartBackHandler({ fallbackPath: resolve('/endpoints') })}
+ onBack={goBackToEndpoints}
/>
- <div class="flex flex-col">
+ <div class="flex items-start gap-2">
+ <Button variant="outline" size="sm" onclick={() => { offsetInput = offsetMs > 0 ? String(offsetMs) : ''; reasonInput = reason; showSlowDialog = true; }}>
+ <Snail class="h-4 w-4" />
+ {offsetMs > 0 ? `+${offsetMs}ms offset` : 'Expected Performance'}
+ </Button>
<TimeRangePicker
bind:fromDate
bind:toDate
@@ -284,6 +371,18 @@
</div>
</div>
+ {#if offsetMs > 0}
+ <div class="flex items-center gap-2 rounded-md border border-border bg-muted/50 px-4 py-3 text-sm">
+ <Snail class="h-4 w-4 shrink-0 text-muted-foreground" />
+ <span>
+ <span class="font-medium">Expected Performance:</span> +{offsetMs}ms offset applied.
+ {#if reason}
+ {reason}
+ {/if}
+ </span>
+ </div>
+ {/if}
+
<!-- Endpoint Stats -->
{#if stats}
<div class="grid grid-cols-2 gap-4 md:grid-cols-4 lg:grid-cols-7">
@@ -435,3 +534,38 @@
/>
{/if}
</div>
+
+<AlertDialog.Root bind:open={showSlowDialog}>
+ <AlertDialog.Content>
+ <AlertDialog.Header>
+ <AlertDialog.Title>Expected Performance</AlertDialog.Title>
+ <AlertDialog.Description>
+ Set a time offset for endpoints that are expected to be slow (e.g., report generation, data exports).
+ The offset adjusts impact score thresholds so the endpoint isn't flagged as unhealthy.
+ </AlertDialog.Description>
+ </AlertDialog.Header>
+ <div class="space-y-4 py-4">
+ <div>
+ <label for="offset-input" class="text-sm font-medium">Offset (ms)</label>
+ <Input id="offset-input" type="number" bind:value={offsetInput} placeholder="e.g., 2000" min="0" class="mt-1.5" />
+ <p class="text-xs text-muted-foreground mt-1.5">
+ How many extra milliseconds above the default 750ms threshold are acceptable for this endpoint.
+ Set to 0 to remove the offset.
+ </p>
+ </div>
+ <div>
+ <label for="reason-input" class="text-sm font-medium">Reason</label>
+ <Input id="reason-input" type="text" bind:value={reasonInput} placeholder="e.g., generates large PDF reports" class="mt-1.5" />
+ <p class="text-xs text-muted-foreground mt-1.5">
+ Explain why this endpoint is expected to be slow.
+ </p>
+ </div>
+ </div>
+ <AlertDialog.Footer>
+ <Button variant="outline" onclick={() => showSlowDialog = false} disabled={slowLoading}>Cancel</Button>
+ <Button onclick={saveSlowEndpoint} disabled={slowLoading}>
+ {slowLoading ? 'Saving...' : 'Save'}
+ </Button>
+ </AlertDialog.Footer>
+ </AlertDialog.Content>
+</AlertDialog.Root>