Skip to content

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

progress with endpoints having a simple graph as well

dduxfc4d05c3d62b
diff --git a/backend/app/cache/project_cache.go b/backend/app/cache/project_cache.go
index b08d1767..5142825b 100644
--- a/backend/app/cache/project_cache.go
+++ b/backend/app/cache/project_cache.go
@@ -18,18 +18,15 @@ type projectCache struct {
lastRefresh time.Time
}
-// ProjectCache is the global project cache instance
var ProjectCache = &projectCache{
projects: make(map[string]*models.Project),
projectsById: make(map[uuid.UUID]*models.Project),
}
-// Init initializes the cache by loading all projects from the database
func (c *projectCache) Init(ctx context.Context) error {
return c.Refresh(ctx)
}
-// Refresh reloads all projects from the database into the cache
func (c *projectCache) Refresh(ctx context.Context) error {
projects, err := repositories.ProjectRepository.FindAll(ctx)
if err != nil {
@@ -52,21 +49,18 @@ func (c *projectCache) Refresh(ctx context.Context) error {
return nil
}
-// GetByToken returns a project by its token, or nil if not found
func (c *projectCache) GetByToken(token string) *models.Project {
c.mu.RLock()
defer c.mu.RUnlock()
return c.projects[token]
}
-// GetById returns a project by its ID, or nil if not found
func (c *projectCache) GetById(id uuid.UUID) *models.Project {
c.mu.RLock()
defer c.mu.RUnlock()
return c.projectsById[id]
}
-// GetAll returns all cached projects sorted by created_at (oldest first)
func (c *projectCache) GetAll() []*models.Project {
c.mu.RLock()
defer c.mu.RUnlock()
@@ -76,7 +70,6 @@ func (c *projectCache) GetAll() []*models.Project {
result = append(result, proj)
}
- // Sort by CreatedAt ascending (oldest first, newest last)
sort.Slice(result, func(i, j int) bool {
return result[i].CreatedAt.Before(result[j].CreatedAt)
})
@@ -84,7 +77,6 @@ func (c *projectCache) GetAll() []*models.Project {
return result
}
-// AddProject adds a project to the cache
func (c *projectCache) AddProject(proj *models.Project) {
c.mu.Lock()
defer c.mu.Unlock()
@@ -92,7 +84,6 @@ func (c *projectCache) AddProject(proj *models.Project) {
c.projectsById[proj.Id] = proj
}
-// LastRefresh returns the time of the last cache refresh
func (c *projectCache) LastRefresh() time.Time {
c.mu.RLock()
defer c.mu.RUnlock()
diff --git a/backend/app/controllers/dashboard.controller.go b/backend/app/controllers/dashboard.controller.go
index 511c798b..666c1d71 100644
--- a/backend/app/controllers/dashboard.controller.go
+++ b/backend/app/controllers/dashboard.controller.go
@@ -69,7 +69,6 @@ func (d dashboardController) GetDashboard(c *gin.Context) {
}
serversParam := c.Query("servers")
- // Parse selected servers
var selectedServers []string
if serversParam != "" {
selectedServers = strings.Split(serversParam, ",")
@@ -78,7 +77,6 @@ func (d dashboardController) GetDashboard(c *gin.Context) {
now := time.Now()
var start, end time.Time
- // Parse fromDate parameter
if fromDateStr := c.Query("fromDate"); fromDateStr != "" {
if parsed, err := time.Parse(time.RFC3339, fromDateStr); err == nil {
start = parsed
@@ -89,7 +87,6 @@ func (d dashboardController) GetDashboard(c *gin.Context) {
start = now.Add(-24 * time.Hour)
}
- // Parse toDate parameter
if toDateStr := c.Query("toDate"); toDateStr != "" {
if parsed, err := time.Parse(time.RFC3339, toDateStr); err == nil {
end = parsed
diff --git a/backend/app/controllers/endpoint.controller.go b/backend/app/controllers/endpoint.controller.go
index 6a8d61c8..a1c06790 100644
--- a/backend/app/controllers/endpoint.controller.go
+++ b/backend/app/controllers/endpoint.controller.go
@@ -38,6 +38,14 @@ type EndpointInstancesResponse struct {
Pagination Pagination `json:"pagination"`
}
+type EndpointStackedChartRequest struct {
+ ProjectId uuid.UUID `json:"projectId"`
+ FromDate time.Time `json:"fromDate"`
+ ToDate time.Time `json:"toDate"`
+ MetricType string `json:"metricType"` // total_time, p50, p95, p99
+ IntervalMinutes int `json:"intervalMinutes"` // bucket size
+}
+
func (e endpointController) FindAllEndpoints(c *gin.Context) {
var request EndpointSearchRequest
if err := c.ShouldBindJSON(&request); err != nil {
@@ -130,4 +138,31 @@ func (e endpointController) FindByEndpoint(c *gin.Context) {
})
}
+func (e endpointController) GetStackedChart(c *gin.Context) {
+ var request EndpointStackedChartRequest
+ if err := c.ShouldBindJSON(&request); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+
+ // Validate interval
+ if request.IntervalMinutes < 1 {
+ request.IntervalMinutes = 5 // default to 5 minutes
+ }
+
+ // Validate metric type
+ validMetrics := map[string]bool{"total_time": true, "p50": true, "p95": true, "p99": true}
+ if !validMetrics[request.MetricType] {
+ request.MetricType = "total_time" // default
+ }
+
+ data, err := repositories.EndpointRepository.GetEndpointStackedChart(c, request.ProjectId, request.FromDate, request.ToDate, request.IntervalMinutes, request.MetricType)
+ if err != nil {
+ c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading stacked chart data: %w", err))
+ return
+ }
+
+ c.JSON(http.StatusOK, data)
+}
+
var EndpointController = endpointController{}
diff --git a/backend/app/controllers/metrics.controller.go b/backend/app/controllers/metrics.controller.go
index 0898367d..ca04d053 100644
--- a/backend/app/controllers/metrics.controller.go
+++ b/backend/app/controllers/metrics.controller.go
@@ -244,9 +244,7 @@ func (m metricsController) GetServerMetrics(c *gin.Context) {
})
}
-// parseTimeRange extracts fromDate and toDate from query params, defaults to last 24h
func parseTimeRange(c *gin.Context, now time.Time) (start, end time.Time) {
- // Parse fromDate parameter
if fromDateStr := c.Query("fromDate"); fromDateStr != "" {
if parsed, err := time.Parse(time.RFC3339, fromDateStr); err == nil {
start = parsed
@@ -257,7 +255,6 @@ func parseTimeRange(c *gin.Context, now time.Time) (start, end time.Time) {
start = now.Add(-24 * time.Hour)
}
- // Parse toDate parameter
if toDateStr := c.Query("toDate"); toDateStr != "" {
if parsed, err := time.Parse(time.RFC3339, toDateStr); err == nil {
end = parsed
diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.go
index e9651dd7..1b45ee8d 100644
--- a/backend/app/controllers/routes.go
+++ b/backend/app/controllers/routes.go
@@ -45,6 +45,7 @@ func RegisterControllers(router *gin.RouterGroup) {
router.POST("/endpoints", middleware.UseAppAuth, EndpointController.FindAllEndpoints)
router.POST("/endpoints/grouped", middleware.UseAppAuth, EndpointController.FindGroupedByEndpoint)
router.POST("/endpoints/endpoint", middleware.UseAppAuth, EndpointController.FindByEndpoint)
+ router.POST("/endpoints/chart", middleware.UseAppAuth, EndpointController.GetStackedChart)
router.POST("/endpoints/:endpointId", middleware.UseAppAuth, EndpointDetailController.GetEndpointDetail)
// Tasks
diff --git a/backend/app/models/endpoint.model.go b/backend/app/models/endpoint.model.go
index 9756be3b..7d5f4ae3 100644
--- a/backend/app/models/endpoint.model.go
+++ b/backend/app/models/endpoint.model.go
@@ -43,3 +43,16 @@ type EndpointDetailStats struct {
ErrorRate float64 `json:"errorRate"` // percentage
Throughput float64 `json:"throughput"` // requests per minute
}
+
+// EndpointTimeSeriesPoint represents a single data point in a time series for endpoint charts
+type EndpointTimeSeriesPoint struct {
+ Timestamp time.Time `json:"timestamp"`
+ Endpoint string `json:"endpoint"`
+ Value float64 `json:"value"`
+}
+
+// EndpointStackedChartResponse contains the data for rendering a stacked area chart
+type EndpointStackedChartResponse struct {
+ Endpoints []string `json:"endpoints"` // Top 5 + "Other"
+ Series []EndpointTimeSeriesPoint `json:"series"`
+}
diff --git a/backend/app/repositories/endpoint.repository.go b/backend/app/repositories/endpoint.repository.go
index 80793180..e112b716 100644
--- a/backend/app/repositories/endpoint.repository.go
+++ b/backend/app/repositories/endpoint.repository.go
@@ -74,7 +74,6 @@ func (e *endpointRepository) FindAll(ctx context.Context, projectId uuid.UUID, f
if err := rows.Scan(&t.Id, &t.ProjectId, &t.Endpoint, &t.Duration, &t.RecordedAt, &t.StatusCode, &t.BodySize, &t.ClientIP, &scopeJSON, &t.AppVersion, &t.ServerName); err != nil {
return nil, 0, err
}
- // Parse scope JSON
if scopeJSON != "" && scopeJSON != "{}" {
if err := json.Unmarshal([]byte(scopeJSON), &t.Scope); err != nil {
t.Scope = nil
@@ -215,7 +214,6 @@ func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.
if err := rows.Scan(&t.Id, &t.ProjectId, &t.Endpoint, &t.Duration, &t.RecordedAt, &t.StatusCode, &t.BodySize, &t.ClientIP, &scopeJSON, &t.AppVersion, &t.ServerName); err != nil {
return nil, 0, err
}
- // Parse scope JSON
if scopeJSON != "" && scopeJSON != "{}" {
if err := json.Unmarshal([]byte(scopeJSON), &t.Scope); err != nil {
t.Scope = nil
@@ -248,7 +246,6 @@ func (e *endpointRepository) FindById(ctx context.Context, projectId, endpointId
return nil, err
}
- // Parse scope JSON
if scopeJSON != "" && scopeJSON != "{}" {
if err := json.Unmarshal([]byte(scopeJSON), &t.Scope); err != nil {
t.Scope = nil
@@ -533,4 +530,134 @@ func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId uui
return &stats, nil
}
+// GetEndpointStackedChart returns time-bucketed data for top 5 endpoints by metric + "Other"
+func (e *endpointRepository) GetEndpointStackedChart(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int, metricType string) (*models.EndpointStackedChartResponse, error) {
+ // Step 1: Get top 5 endpoints ranked by selected metric
+ var rankQuery string
+ switch metricType {
+ case "total_time":
+ rankQuery = `SELECT endpoint, count() * quantile(0.5)(duration) / 1000000 as metric_value
+ FROM endpoints
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
+ GROUP BY endpoint
+ ORDER BY metric_value DESC
+ LIMIT 5`
+ case "p95":
+ rankQuery = `SELECT endpoint, quantile(0.95)(duration) / 1000000 as metric_value
+ FROM endpoints
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
+ GROUP BY endpoint
+ ORDER BY metric_value DESC
+ LIMIT 5`
+ case "p99":
+ rankQuery = `SELECT endpoint, quantile(0.99)(duration) / 1000000 as metric_value
+ FROM endpoints
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
+ GROUP BY endpoint
+ ORDER BY metric_value DESC
+ LIMIT 5`
+ default: // p50
+ rankQuery = `SELECT endpoint, quantile(0.5)(duration) / 1000000 as metric_value
+ FROM endpoints
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
+ GROUP BY endpoint
+ ORDER BY metric_value DESC
+ LIMIT 5`
+ }
+
+ rows, err := (*chdb.Conn).Query(ctx, rankQuery, projectId, start, end)
+ if err != nil {
+ return nil, err
+ }
+
+ var topEndpoints []string
+ for rows.Next() {
+ var endpoint string
+ var metricValue float64
+ if err := rows.Scan(&endpoint, &metricValue); err != nil {
+ rows.Close()
+ return nil, err
+ }
+ topEndpoints = append(topEndpoints, endpoint)
+ }
+ rows.Close()
+
+ if len(topEndpoints) == 0 {
+ return &models.EndpointStackedChartResponse{
+ Endpoints: []string{},
+ Series: []models.EndpointTimeSeriesPoint{},
+ }, nil
+ }
+
+ // Step 2: Build the time-bucketed query with top endpoints + "Other"
+ var metricExpr string
+ switch metricType {
+ case "total_time":
+ metricExpr = "count() * quantile(0.5)(duration) / 1000000"
+ case "p95":
+ metricExpr = "quantile(0.95)(duration) / 1000000"
+ case "p99":
+ metricExpr = "quantile(0.99)(duration) / 1000000"
+ default: // p50
+ metricExpr = "quantile(0.5)(duration) / 1000000"
+ }
+
+ // Build CASE expression for categorizing endpoints
+ caseExpr := "multiIf("
+ for i, ep := range topEndpoints {
+ caseExpr += "endpoint = ?, '" + ep + "', "
+ _ = i // use index in iteration
+ }
+ caseExpr += "'Other')"
+
+ timeSeriesQuery := `SELECT
+ toStartOfInterval(recorded_at, INTERVAL ? MINUTE) as bucket,
+ ` + caseExpr + ` as endpoint_category,
+ ` + metricExpr + ` as metric_value
+ FROM endpoints
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
+ GROUP BY bucket, endpoint_category
+ ORDER BY bucket ASC, endpoint_category ASC`
+
+ // Build args: interval, top endpoints for CASE, then project_id, start, end
+ args := make([]interface{}, 0, len(topEndpoints)+4)
+ args = append(args, intervalMinutes)
+ for _, ep := range topEndpoints {
+ args = append(args, ep)
+ }
+ args = append(args, projectId, start, end)
+
+ rows, err = (*chdb.Conn).Query(ctx, timeSeriesQuery, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var series []models.EndpointTimeSeriesPoint
+ for rows.Next() {
+ var p models.EndpointTimeSeriesPoint
+ if err := rows.Scan(&p.Timestamp, &p.Endpoint, &p.Value); err != nil {
+ return nil, err
+ }
+ series = append(series, p)
+ }
+
+ // Build final endpoint list (top 5 + Other if there are other endpoints)
+ endpointSet := make(map[string]bool)
+ for _, p := range series {
+ endpointSet[p.Endpoint] = true
+ }
+
+ finalEndpoints := make([]string, 0, len(topEndpoints)+1)
+ finalEndpoints = append(finalEndpoints, topEndpoints...)
+ if endpointSet["Other"] {
+ finalEndpoints = append(finalEndpoints, "Other")
+ }
+
+ return &models.EndpointStackedChartResponse{
+ Endpoints: finalEndpoints,
+ Series: series,
+ }, nil
+}
+
var EndpointRepository = endpointRepository{}
diff --git a/backend/app/repositories/exception_stack_trace.repository.go b/backend/app/repositories/exception_stack_trace.repository.go
index 22d59805..fada8eed 100644
--- a/backend/app/repositories/exception_stack_trace.repository.go
+++ b/backend/app/repositories/exception_stack_trace.repository.go
@@ -52,7 +52,6 @@ func (e *exceptionStackTraceRepository) CountBetween(ctx context.Context, projec
func (e *exceptionStackTraceRepository) FindGrouped(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, search string, searchType string, includeArchived bool) ([]models.ExceptionGroup, int64, error) {
offset := (page - 1) * pageSize
- // Parse sort direction from orderBy (e.g., "last_seen_asc" -> "last_seen", "ASC")
sortDirection := "DESC"
if strings.HasSuffix(orderBy, "_asc") {
orderBy = strings.TrimSuffix(orderBy, "_asc")
@@ -178,7 +177,6 @@ func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, projectI
return nil, nil, 0, err
}
o.IsMessage = isMessage == 1
- // Parse scope JSON
if scopeJSON != "" && scopeJSON != "{}" {
if err := json.Unmarshal([]byte(scopeJSON), &o.Scope); err != nil {
o.Scope = nil // If parsing fails, leave scope as nil
@@ -343,7 +341,6 @@ func (e *exceptionStackTraceRepository) FindExceptionByTransactionId(ctx context
}
est.IsMessage = isMessage == 1
- // Parse scope JSON
if scopeJSON != "" && scopeJSON != "{}" {
if err := json.Unmarshal([]byte(scopeJSON), &est.Scope); err != nil {
est.Scope = nil
@@ -413,7 +410,6 @@ func (e *exceptionStackTraceRepository) FindById(ctx context.Context, projectId
}
est.IsMessage = isMessage == 1
- // Parse scope JSON
if scopeJSON != "" && scopeJSON != "{}" {
if err := json.Unmarshal([]byte(scopeJSON), &est.Scope); err != nil {
est.Scope = nil
diff --git a/backend/app/repositories/task.repository.go b/backend/app/repositories/task.repository.go
index 9e2825da..bc136959 100644
--- a/backend/app/repositories/task.repository.go
+++ b/backend/app/repositories/task.repository.go
@@ -72,7 +72,6 @@ func (e *taskRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromD
if err := rows.Scan(&t.Id, &t.ProjectId, &t.TaskName, &t.Duration, &t.RecordedAt, &t.ClientIP, &scopeJSON, &t.AppVersion, &t.ServerName); err != nil {
return nil, 0, err
}
- // Parse scope JSON
if scopeJSON != "" && scopeJSON != "{}" {
if err := json.Unmarshal([]byte(scopeJSON), &t.Scope); err != nil {
t.Scope = nil
@@ -188,7 +187,6 @@ func (e *taskRepository) FindByTaskName(ctx context.Context, projectId uuid.UUID
if err := rows.Scan(&t.Id, &t.ProjectId, &t.TaskName, &t.Duration, &t.RecordedAt, &t.ClientIP, &scopeJSON, &t.AppVersion, &t.ServerName); err != nil {
return nil, 0, err
}
- // Parse scope JSON
if scopeJSON != "" && scopeJSON != "{}" {
if err := json.Unmarshal([]byte(scopeJSON), &t.Scope); err != nil {
t.Scope = nil
@@ -221,7 +219,6 @@ func (e *taskRepository) FindById(ctx context.Context, projectId, taskId uuid.UU
return nil, err
}
- // Parse scope JSON
if scopeJSON != "" && scopeJSON != "{}" {
if err := json.Unmarshal([]byte(scopeJSON), &t.Scope); err != nil {
t.Scope = nil
diff --git a/backend/backend b/backend/backend
index f8529a15..8e9d92bb 100755
Binary files a/backend/backend and b/backend/backend differ
diff --git a/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte b/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte
new file mode 100644
index 00000000..09446548
--- /dev/null
+++ b/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte
@@ -0,0 +1,414 @@
+<script lang="ts">
+ import { scaleUtc, scaleLinear } from 'd3-scale';
+ import { stack, area, stackOrderReverse } from 'd3-shape';
+ import { min, max } from 'd3-array';
+ import { formatDateTime } from '$lib/utils/formatters';
+ import { getTimezone } from '$lib/state/timezone.svelte';
+
+ type DataPoint = {
+ timestamp: Date;
+ endpoint: string;
+ value: number;
+ };
+
+ type StackedData = {
+ [key: string]: number | Date;
+ timestamp: Date;
+ };
+
+ let {
+ endpoints = [],
+ series = [],
+ height = 220,
+ padding = { top: 10, right: 4, bottom: 20, left: 55 },
+ unit = 'ms',
+ formatValue
+ } = $props<{
+ endpoints: string[];
+ series: DataPoint[];
+ height?: number;
+ padding?: { top: number; right: number; bottom: number; left: number };
+ unit?: string;
+ formatValue?: (value: number) => string;
+ }>();
+
+ const tz = $derived(getTimezone());
+
+ // Chart colors using CSS variables
+ const chartColors = [
+ 'var(--chart-1)',
+ 'var(--chart-2)',
+ 'var(--chart-3)',
+ 'var(--chart-4)',
+ 'var(--chart-5)',
+ 'var(--muted-foreground)' // For "Other"
+ ];
+
+ let containerRef = $state<HTMLDivElement | null>(null);
+ let width = $state(300);
+
+ // Hover state
+ let isHovering = $state(false);
+ let mouseX = $state(0);
+
+ // Observe container width
+ $effect(() => {
+ if (!containerRef) return;
+
+ const observer = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ width = entry.contentRect.width;
+ }
+ });
+
+ observer.observe(containerRef);
+ return () => observer.disconnect();
+ });
+
+ // Chart dimensions
+ const chartWidth = $derived(Math.max(0, width - padding.left - padding.right));
+ const chartHeight = $derived(Math.max(0, height - padding.top - padding.bottom));
+
+ // Transform series data to stacked format
+ const stackedData = $derived(() => {
+ if (series.length === 0 || endpoints.length === 0) return [];
+
+ // Group by timestamp
+ const byTimestamp = new Map<number, StackedData>();
+
+ for (const point of series) {
+ const ts = point.timestamp.getTime();
+ if (!byTimestamp.has(ts)) {
+ const entry: StackedData = { timestamp: point.timestamp };
+ // Initialize all endpoints to 0
+ for (const ep of endpoints) {
+ entry[ep] = 0;
+ }
+ byTimestamp.set(ts, entry);
+ }
+ const entry = byTimestamp.get(ts)!;
+ entry[point.endpoint] = point.value;
+ }
+
+ // Sort by timestamp
+ return Array.from(byTimestamp.values()).sort(
+ (a, b) => a.timestamp.getTime() - b.timestamp.getTime()
+ );
+ });
+
+ // Calculate domains
+ const xMin = $derived(() => {
+ const data = stackedData();
+ if (data.length === 0) return new Date();
+ return min(data, (d) => d.timestamp) ?? new Date();
+ });
+
+ const xMax = $derived(() => {
+ const data = stackedData();
+ if (data.length === 0) return new Date();
+ return max(data, (d) => d.timestamp) ?? new Date();
+ });
+
+ // Helper to get numeric value from StackedData
+ function getNumericValue(d: StackedData, key: string): number {
+ const val = d[key];
+ return typeof val === 'number' ? val : 0;
+ }
+
+ // Calculate max stacked value
+ const yMax = $derived(() => {
+ const data = stackedData();
+ if (data.length === 0 || endpoints.length === 0) return 0;
+
+ let maxSum = 0;
+ for (const d of data) {
+ let sum = 0;
+ for (const ep of endpoints) {
+ sum += getNumericValue(d, ep);
+ }
+ maxSum = Math.max(maxSum, sum);
+ }
+ return maxSum;
+ });
+
+ // Add padding to y domain
+ const yDomainMax = $derived(yMax() * 1.1 || 1);
+
+ // Scales
+ const xScale = $derived(
+ scaleUtc()
+ .domain([xMin(), xMax()])
+ .range([0, chartWidth])
+ );
+
+ const yScale = $derived(
+ scaleLinear()
+ .domain([0, yDomainMax])
+ .range([chartHeight, 0])
+ );
+
+ // Generate Y axis ticks
+ const yTicks = $derived(() => yScale.ticks(4));
+
+ // Format Y axis label
+ function formatYLabel(value: number): string {
+ if (value >= 1000000) return (value / 1000000).toFixed(1) + 'M';
+ if (value >= 1000) return (value / 1000).toFixed(1) + 'k';
+ if (Number.isInteger(value)) return value.toString();
+ return value.toFixed(1);
+ }
+
+ // Generate stacked area paths
+ const stackedAreas = $derived(() => {
+ const data = stackedData();
+ if (data.length === 0 || endpoints.length === 0) return [];
+
+ const stackGen = stack<StackedData>()
+ .keys(endpoints)
+ .order(stackOrderReverse);
+
+ const stackedSeries = stackGen(data);
+
+ const areaGen = area<[number, number]>()
+ .x((d, i) => xScale(data[i].timestamp))
+ .y0((d) => yScale(d[0]))
+ .y1((d) => yScale(d[1]));
+
+ return stackedSeries.map((s, i) => ({
+ key: s.key,
+ path: areaGen(s as unknown as [number, number][]) || '',
+ color: chartColors[i % chartColors.length]
+ }));
+ });
+
+ const hasData = $derived(stackedData().length > 0 && endpoints.length > 0);
+
+ // Check if mouse X is within the chart area
+ function isInChartArea(): boolean {
+ return mouseX >= padding.left && mouseX <= width - padding.right;
+ }
+
+ // Calculate time based on X position
+ function getTimeAtPosition(x: number): Date {
+ if (chartWidth <= 0) return xMin();
+ const chartX = x - padding.left;
+ const percentage = Math.max(0, Math.min(1, chartX / chartWidth));
+ const timeDiff = xMax().getTime() - xMin().getTime();
+ return new Date(xMin().getTime() + timeDiff * percentage);
+ }
+
+ // Find the closest data point to a given time
+ function getDataAtTime(time: Date): StackedData | null {
+ const data = stackedData();
+ if (data.length === 0) return null;
+
+ const targetMs = time.getTime();
+ let closest: StackedData | null = null;
+ let minDiff = Infinity;
+
+ for (const d of data) {
+ const diff = Math.abs(d.timestamp.getTime() - targetMs);
+ if (diff < minDiff) {
+ minDiff = diff;
+ closest = d;
+ }
+ }
+
+ return closest;
+ }
+
+ // Calculate time based on mouse X position
+ const calculatedTime = $derived(() => {
+ if (!isHovering) return null;
+ return getTimeAtPosition(mouseX);
+ });
+
+ // Calculate the data point at the current hover position
+ const calculatedData = $derived(() => {
+ const time = calculatedTime();
+ if (!time) return null;
+ return getDataAtTime(time);
+ });
+
+ // Format value for display
+ function formatDisplayValue(value: number): string {
+ if (formatValue) return formatValue(value);
+ if (Number.isInteger(value)) return value.toString();
+ if (Math.abs(value) < 0.01) return value.toFixed(4);
+ if (Math.abs(value) < 1) return value.toFixed(2);
+ if (Math.abs(value) < 10) return value.toFixed(1);
+ return Math.round(value).toString();
+ }
+
+ function handleMouseMove(e: MouseEvent) {
+ if (!containerRef) return;
+ const rect = containerRef.getBoundingClientRect();
+ mouseX = e.clientX - rect.left;
+ }
+
+ function handleMouseEnter() {
+ isHovering = true;
+ }
+
+ function handleMouseLeave() {
+ isHovering = false;
+ }
+
+ function formatTime(date: Date | null): string {
+ if (!date) return '';
+ return formatDateTime(date, { timezone: tz, format: 'time' });
+ }
+
+ // Get color for an endpoint
+ function getEndpointColor(endpoint: string): string {
+ const idx = endpoints.indexOf(endpoint);
+ if (idx === -1) return chartColors[chartColors.length - 1];
+ return chartColors[idx % chartColors.length];
+ }
+
+ // Truncate long endpoint names for legend
+ function truncateEndpoint(endpoint: string, maxLen: number = 30): string {
+ if (endpoint.length <= maxLen) return endpoint;
+ return endpoint.slice(0, maxLen - 3) + '...';
+ }
+</script>
+
+<div class="flex flex-col gap-2">
+ <div
+ bind:this={containerRef}
+ class="relative select-none w-full"
+ style="height: {height}px; cursor: {isInChartArea() ? 'crosshair' : 'default'};"
+ onmouseenter={handleMouseEnter}
+ onmouseleave={handleMouseLeave}
+ onmousemove={handleMouseMove}
+ role="application"
+ aria-label="Stacked area chart"
+ >
+ {#if hasData && chartWidth > 0}
+ <svg {width} {height}>
+ <g transform="translate({padding.left}, {padding.top})">
+ <!-- Y axis grid lines -->
+ {#each yTicks() as tick}
+ <line
+ x1={0}
+ y1={yScale(tick)}
+ x2={chartWidth}
+ y2={yScale(tick)}
+ stroke="currentColor"
+ class="text-border"
+ stroke-width="1"
+ stroke-dasharray="4 4"
+ />
+ {/each}
+
+ <!-- Y axis labels -->
+ {#each yTicks() as tick}
+ <text
+ x={-8}
+ y={yScale(tick)}
+ text-anchor="end"
+ dominant-baseline="middle"
+ fill="currentColor"
+ class="text-muted-foreground"
+ font-size="10"
+ >
+ {formatYLabel(tick)}
+ </text>
+ {/each}
+
+ <!-- X axis line -->
+ <line
+ x1={0}
+ y1={chartHeight}
+ x2={chartWidth}
+ y2={chartHeight}
+ stroke="currentColor"
+ class="text-border"
+ stroke-width="1"
+ />
+
+ <!-- Y axis line -->
+ <line
+ x1={0}
+ y1={0}
+ x2={0}
+ y2={chartHeight}
+ stroke="currentColor"
+ class="text-border"
+ stroke-width="1"
+ />
+
+ <!-- Stacked areas -->
+ {#each stackedAreas() as area}
+ <path
+ d={area.path}
+ fill={area.color}
+ fill-opacity="0.7"
+ stroke={area.color}
+ stroke-width="1"
+ />
+ {/each}
+ </g>
+ </svg>
+ {:else}
+ <div class="flex h-full items-center justify-center text-sm text-muted-foreground">
+ No data in this period
+ </div>
+ {/if}
+
+ <!-- Hover tooltip -->
+ {#if isHovering && isInChartArea() && calculatedData()}
+ {@const clampedX = Math.max(padding.left, Math.min(mouseX, width - padding.right))}
+ {@const data = calculatedData()}
+
+ <!-- Vertical line -->
+ <div
+ class="absolute top-0 bottom-0 w-px bg-muted-foreground/50 pointer-events-none"
+ style="left: {clampedX}px;"
+ ></div>
+
+ <!-- Value tooltip -->
+ {#if data}
+ <div
+ class="absolute top-0 -translate-x-1/2 -translate-y-full pointer-events-none z-10"
+ style="left: {clampedX}px;"
+ >
+ <div class="bg-foreground text-background rounded px-2 py-1.5 text-xs font-medium whitespace-nowrap shadow-lg mb-1 flex flex-col gap-0.5">
+ {#each endpoints as endpoint}
+ {@const value = getNumericValue(data, endpoint)}
+ {#if value > 0}
+ <div class="flex items-center gap-1.5">
+ <span class="h-2 w-2 rounded-full flex-shrink-0" style="background-color: {getEndpointColor(endpoint)};"></span>
+ <span class="truncate max-w-[200px]" title={endpoint}>{truncateEndpoint(endpoint, 25)}</span>
+ <span class="ml-auto tabular-nums">{formatDisplayValue(value)}{unit ? ` ${unit}` : ''}</span>
+ </div>
+ {/if}
+ {/each}
+ </div>
+ </div>
+ {/if}
+
+ <!-- Time label -->
+ <div
+ class="absolute bottom-0 -translate-x-1/2 translate-y-full pointer-events-none"
+ style="left: {clampedX}px;"
+ >
+ <div class="bg-background border border-border rounded px-1.5 py-0.5 text-[10px] text-muted-foreground whitespace-nowrap shadow-sm mt-1">
+ {formatTime(calculatedTime())}
+ </div>
+ </div>
+ {/if}
+ </div>
+
+ <!-- Legend -->
+ {#if hasData}
+ <div class="flex flex-wrap gap-x-4 gap-y-1 px-2 text-xs text-muted-foreground">
+ {#each endpoints as endpoint, i}
+ <div class="flex items-center gap-1.5">
+ <span class="h-2 w-2 rounded-full flex-shrink-0" style="background-color: {chartColors[i % chartColors.length]};"></span>
+ <span class="truncate max-w-[180px]" title={endpoint}>{truncateEndpoint(endpoint, 25)}</span>
+ </div>
+ {/each}
+ </div>
+ {/if}
+</div>
diff --git a/frontend/src/routes/endpoints/+page.svelte b/frontend/src/routes/endpoints/+page.svelte
index 51743d2b..137d024e 100644
--- a/frontend/src/routes/endpoints/+page.svelte
+++ b/frontend/src/routes/endpoints/+page.svelte
@@ -4,9 +4,11 @@
import { formatDuration, toUTCISO, calendarDateTimeToLuxon } from '$lib/utils/formatters';
import { getTimezone } from '$lib/state/timezone.svelte';
import * as Table from "$lib/components/ui/table";
+ import * as Card from "$lib/components/ui/card";
import { Button } from "$lib/components/ui/button";
import { LoadingCircle } from "$lib/components/ui/loading-circle";
- import * as Select from "$lib/components/ui/select";
+ import * as DropdownMenu from "$lib/components/ui/dropdown-menu/index.js";
+ import { ChevronDown, Check } from 'lucide-svelte';
import { TracewayTableHeader } from "$lib/components/ui/traceway-table-header";
import { ImpactBadge } from "$lib/components/ui/impact-badge";
import { TableEmptyState } from "$lib/components/ui/table-empty-state";
@@ -17,6 +19,7 @@
import { createRowClickHandler } from '$lib/utils/navigation';
import { resolve } from '$app/paths';
import PageHeader from '$lib/components/issues/page-header.svelte';
+ import D3StackedAreaChart from '$lib/components/dashboard/d3-stacked-area-chart.svelte';
import {
presetMinutes,
getTimeRangeFromPreset,
@@ -32,6 +35,7 @@
handleSortClick,
type SortDirection
} from '$lib/utils/sort-storage';
+ import { ChartLine } from '@lucide/svelte';
const timezone = $derived(getTimezone());
@@ -48,10 +52,35 @@
type SortField = 'count' | 'p50_duration' | 'p95_duration' | 'p99_duration' | 'last_seen' | 'impact';
+ type ChartDataPoint = {
+ timestamp: Date;
+ endpoint: string;
+ value: number;
+ };
+
+ type ChartResponse = {
+ endpoints: string[];
+ series: { timestamp: string; endpoint: string; value: number }[];
+ };
+
+ // Metric options for the chart
+ const metricOptions = [
+ { value: 'total_time', label: 'Total time' },
+ { value: 'p50', label: 'Average response time' },
+ { value: 'p95', label: 'Slow response time' },
+ { value: 'p99', label: 'Awful response time' }
+ ];
+
let endpoints = $state<EndpointStats[]>([]);
let loading = $state(true);
let error = $state('');
+ // Chart state
+ let chartEndpoints = $state<string[]>([]);
+ let chartSeries = $state<ChartDataPoint[]>([]);
+ let chartLoading = $state(true);
+ let selectedMetric = $state('total_time');
+
// Pagination State
let page = $state(1);
let pageSize = $state(100);
@@ -143,6 +172,47 @@
return count.toLocaleString();
}
+ // Calculate interval based on time range
+ function calculateInterval(from: Date, to: Date): number {
+ const diffMs = to.getTime() - from.getTime();
+ const diffHours = diffMs / (1000 * 60 * 60);
+
+ if (diffHours <= 1) return 1; // 1 minute
+ if (diffHours <= 24) return 5; // 5 minutes
+ if (diffHours <= 24 * 7) return 60; // 1 hour
+ return 240; // 4 hours
+ }
+
+ async function loadChartData() {
+ chartLoading = true;
+
+ try {
+ const fromStr = getFromDateTimeUTC();
+ const toStr = getToDateTimeUTC();
+ const interval = calculateInterval(new Date(fromStr), new Date(toStr));
+
+ const response = await api.post('/endpoints/chart', {
+ fromDate: fromStr,
+ toDate: toStr,
+ metricType: selectedMetric,
+ intervalMinutes: interval
+ }, { projectId: projectsState.currentProjectId ?? undefined }) as ChartResponse;
+
+ chartEndpoints = response.endpoints || [];
+ chartSeries = (response.series || []).map((s: { timestamp: string; endpoint: string; value: number }) => ({
+ timestamp: new Date(s.timestamp),
+ endpoint: s.endpoint,
+ value: s.value
+ }));
+ } catch (e: any) {
+ console.error('Failed to load chart data:', e);
+ chartEndpoints = [];
+ chartSeries = [];
+ } finally {
+ chartLoading = false;
+ }
+ }
+
async function loadData(pushToHistory = true) {
loading = true;
error = '';
@@ -173,6 +243,9 @@
} finally {
loading = false;
}
+
+ // Also load chart data
+ loadChartData();
}
function handlePageChange(newPage: number) {
@@ -197,6 +270,16 @@
loadData(false);
}
+ function handleMetricChange(value: string) {
+ selectedMetric = value;
+ loadChartData();
+ }
+
+ const selectedMetricLabel = $derived(metricOptions.find(o => o.value === selectedMetric)?.label ?? 'Total time');
+
+ // Get the unit for the selected metric
+ const chartUnit = $derived(selectedMetric === 'total_time' ? 'ms' : 'ms');
+
onMount(() => {
// Add popstate listener for back/forward navigation
window.addEventListener('popstate', handlePopState);
@@ -230,6 +313,47 @@
</div>
</div>
+ <!-- Performance Chart -->
+ <Card.Root class="pt-2">
+ <Card.Header class="flex flex-row items-center justify-between space-y-0 border-b [.border-b]:pb-2 pl-3">
+ <Card.Title class="text-base font-medium flex items-center gap-2">
+ <ChartLine class="h-3.5 w-3.5" />
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger class="flex items-center text-sm gap-0.5 font-medium">
+ {selectedMetricLabel}
+ <ChevronDown class="h-3 w-3" />
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="start" class="w-[200px]">
+ {#each metricOptions as option}
+ <DropdownMenu.Item
+ onclick={() => handleMetricChange(option.value)}
+ class="flex items-center justify-between cursor-pointer"
+ >
+ <span>{option.label}</span>
+ {#if option.value === selectedMetric}
+ <Check class="h-4 w-4" />
+ {/if}
+ </DropdownMenu.Item>
+ {/each}
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Card.Title>
+ </Card.Header>
+ <Card.Content>
+ {#if chartLoading}
+ <div class="flex justify-center items-center h-[220px]">
+ <LoadingCircle size="xlg" />
+ </div>
+ {:else}
+ <D3StackedAreaChart
+ endpoints={chartEndpoints}
+ series={chartSeries}
+ unit={chartUnit}
+ />
+ {/if}
+ </Card.Content>
+ </Card.Root>
+
<!-- Endpoints Table -->
<div class="rounded-md border overflow-hidden">
<Table.Root>