Skip to content

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

upgraded metrics with custom units

dduxed7e500b2071
diff --git a/backend/app/controllers/clientcontrollers/client.controller.go b/backend/app/controllers/clientcontrollers/client.controller.go
index 7a47a782..500a75ee 100644
--- a/backend/app/controllers/clientcontrollers/client.controller.go
+++ b/backend/app/controllers/clientcontrollers/client.controller.go
@@ -179,8 +179,8 @@ func (e clientController) Report(c *gin.Context) {
return
}
- metricNames := collectUniqueMetricNames(metricPointsToInsert)
- go autoRegisterMetrics(projectId, metricNames)
+ metricNames := services.CollectUniqueMetricNames(metricPointsToInsert)
+ go services.AutoRegisterMetrics(projectId, metricNames)
}
err = repositories.SpanRepository.InsertAsync(c, spansToInsert)
@@ -231,27 +231,6 @@ func (e clientController) Report(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
-func collectUniqueMetricNames(points []models.MetricPoint) []string {
- seen := make(map[string]struct{}, len(points))
- var names []string
- for _, p := range points {
- if _, ok := seen[p.Name]; !ok {
- seen[p.Name] = struct{}{}
- names = append(names, p.Name)
- }
- }
- return names
-}
-
-func autoRegisterMetrics(projectId uuid.UUID, names []string) {
- _, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {
- return struct{}{}, repositories.MetricRegistryRepository.EnsureRegistered(tx, projectId, names)
- })
- if err != nil {
- traceway.CaptureException(fmt.Errorf("failed to auto-register metrics: %w", err))
- }
-}
-
var (
errorMessageRe = regexp.MustCompile(`(?m)^(\*?[\w.]+):\s*.+`)
absolutePathRe = regexp.MustCompile(`/[^\s:]+/([^/\s:]+:\d+)`)
diff --git a/backend/app/controllers/metric_query.controller.go b/backend/app/controllers/metric_query.controller.go
index f1dbe2a5..ae38197f 100644
--- a/backend/app/controllers/metric_query.controller.go
+++ b/backend/app/controllers/metric_query.controller.go
@@ -35,7 +35,8 @@ type MetricQueryResponse struct {
}
type MetricQueryResult struct {
- Name string `json:"name"`
+ Name string `json:"name"`
+ Unit string `json:"unit"`
Series map[string][]models.TimeSeriesPoint `json:"series"`
}
@@ -56,6 +57,19 @@ func (c *metricQueryController) Query(ctx *gin.Context) {
req.IntervalMinutes = calculateIntervalMinutes(req.To.Sub(req.From))
}
+ unitMap := make(map[string]string)
+ registry, regErr := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.MetricRegistry, error) {
+ return repositories.MetricRegistryRepository.FindByProject(tx, projectId)
+ })
+ if regErr != nil {
+ traceway.CaptureException(fmt.Errorf("failed to load metric registry for query: %w", regErr))
+ }
+ if regErr == nil {
+ for _, r := range registry {
+ unitMap[r.Name] = r.Unit
+ }
+ }
+
var results []MetricQueryResult
for _, q := range req.Queries {
agg := q.Aggregation
@@ -72,8 +86,14 @@ func (c *metricQueryController) Query(ctx *gin.Context) {
return
}
+ resultUnit := unitMap[q.Name]
+ if agg == "count" {
+ resultUnit = "count"
+ }
+
results = append(results, MetricQueryResult{
Name: q.Name,
+ Unit: resultUnit,
Series: series,
})
}
diff --git a/backend/app/controllers/otelcontrollers/metric_converter.go b/backend/app/controllers/otelcontrollers/metric_converter.go
index 9401da99..80384fce 100644
--- a/backend/app/controllers/otelcontrollers/metric_converter.go
+++ b/backend/app/controllers/otelcontrollers/metric_converter.go
@@ -2,14 +2,22 @@ package otelcontrollers
import (
"github.com/tracewayapp/traceway/backend/app/models"
+ "github.com/tracewayapp/traceway/backend/app/repositories"
"github.com/google/uuid"
colmetricspb "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
+ commonpb "go.opentelemetry.io/proto/otlp/common/v1"
metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"
)
-func convertMetricPoints(projectId uuid.UUID, req *colmetricspb.ExportMetricsServiceRequest) []models.MetricPoint {
+type convertedMetrics struct {
+ Points []models.MetricPoint
+ Entries []repositories.MetricRegistrationEntry
+}
+
+func convertMetricPoints(projectId uuid.UUID, req *colmetricspb.ExportMetricsServiceRequest) convertedMetrics {
var points []models.MetricPoint
+ seenEntries := make(map[string]repositories.MetricRegistrationEntry)
for _, rm := range req.ResourceMetrics {
resAttrs := rm.GetResource().GetAttributes()
@@ -18,19 +26,35 @@ func convertMetricPoints(projectId uuid.UUID, req *colmetricspb.ExportMetricsSer
for _, sm := range rm.ScopeMetrics {
for _, metric := range sm.Metrics {
name := metric.Name
+ unit := metric.Unit
switch data := metric.Data.(type) {
case *metricspb.Metric_Gauge:
points = appendNumberDataPoints(points, projectId, name, sn, data.Gauge.GetDataPoints())
+ if _, ok := seenEntries[name]; !ok {
+ seenEntries[name] = repositories.MetricRegistrationEntry{
+ Name: name,
+ Unit: unit,
+ MetricType: "gauge",
+ }
+ }
case *metricspb.Metric_Sum:
points = appendNumberDataPoints(points, projectId, name, sn, data.Sum.GetDataPoints())
+ if _, ok := seenEntries[name]; !ok {
+ mt := "gauge"
+ if data.Sum.IsMonotonic {
+ mt = "counter"
+ }
+ seenEntries[name] = repositories.MetricRegistrationEntry{
+ Name: name,
+ Unit: unit,
+ MetricType: mt,
+ }
+ }
case *metricspb.Metric_Histogram:
for _, dp := range data.Histogram.GetDataPoints() {
ts := nanoToTime(dp.TimeUnixNano)
- tags := make(map[string]string)
- if sn != "" {
- tags["server_name"] = sn
- }
+ tags := buildTags(sn, dp.Attributes)
if dp.Count > 0 && dp.Sum != nil {
points = append(points, models.MetricPoint{
ProjectId: projectId,
@@ -48,11 +72,33 @@ func convertMetricPoints(projectId uuid.UUID, req *colmetricspb.ExportMetricsSer
RecordedAt: ts,
})
}
+ avgName := name + ".avg"
+ countName := name + ".count"
+ if _, ok := seenEntries[avgName]; !ok {
+ seenEntries[avgName] = repositories.MetricRegistrationEntry{
+ Name: avgName,
+ Unit: unit,
+ MetricType: "gauge",
+ }
+ }
+ if _, ok := seenEntries[countName]; !ok {
+ seenEntries[countName] = repositories.MetricRegistrationEntry{
+ Name: countName,
+ Unit: "count",
+ MetricType: "counter",
+ }
+ }
}
}
}
}
- return points
+
+ entries := make([]repositories.MetricRegistrationEntry, 0, len(seenEntries))
+ for _, e := range seenEntries {
+ entries = append(entries, e)
+ }
+
+ return convertedMetrics{Points: points, Entries: entries}
}
func appendNumberDataPoints(points []models.MetricPoint, projectId uuid.UUID, name, serverName string, dps []*metricspb.NumberDataPoint) []models.MetricPoint {
@@ -64,10 +110,7 @@ func appendNumberDataPoints(points []models.MetricPoint, projectId uuid.UUID, na
case *metricspb.NumberDataPoint_AsInt:
value = float64(v.AsInt)
}
- tags := make(map[string]string)
- if serverName != "" {
- tags["server_name"] = serverName
- }
+ tags := buildTags(serverName, dp.Attributes)
points = append(points, models.MetricPoint{
ProjectId: projectId,
Name: name,
@@ -78,3 +121,14 @@ func appendNumberDataPoints(points []models.MetricPoint, projectId uuid.UUID, na
}
return points
}
+
+func buildTags(serverName string, attrs []*commonpb.KeyValue) map[string]string {
+ tags := extractAttributes(attrs)
+ if tags == nil {
+ tags = make(map[string]string)
+ }
+ if serverName != "" {
+ tags["server_name"] = serverName
+ }
+ return tags
+}
diff --git a/backend/app/controllers/otelcontrollers/otel.controller.go b/backend/app/controllers/otelcontrollers/otel.controller.go
index d6503d98..d2ca6a68 100644
--- a/backend/app/controllers/otelcontrollers/otel.controller.go
+++ b/backend/app/controllers/otelcontrollers/otel.controller.go
@@ -5,6 +5,7 @@ import (
"github.com/tracewayapp/traceway/backend/app/middleware"
"github.com/tracewayapp/traceway/backend/app/models"
"github.com/tracewayapp/traceway/backend/app/repositories"
+ "github.com/tracewayapp/traceway/backend/app/services"
"net/http"
"github.com/gin-gonic/gin"
@@ -99,12 +100,16 @@ func (o otelController) ExportMetrics(c *gin.Context) {
return
}
- points := convertMetricPoints(projectId, req)
- if len(points) > 0 {
- if err := repositories.MetricPointRepository.InsertAsync(c, points); err != nil {
+ result := convertMetricPoints(projectId, req)
+ if len(result.Points) > 0 {
+ if err := repositories.MetricPointRepository.InsertAsync(c, result.Points); err != nil {
c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL metric points: %w", err))
return
}
+
+ if len(result.Entries) > 0 {
+ go services.AutoRegisterMetricsWithUnits(projectId, result.Entries)
+ }
}
writeMetricsResponse(c)
diff --git a/backend/app/repositories/metric_registry.repository.go b/backend/app/repositories/metric_registry.repository.go
index e1202694..0d41381b 100644
--- a/backend/app/repositories/metric_registry.repository.go
+++ b/backend/app/repositories/metric_registry.repository.go
@@ -66,6 +66,49 @@ func (r *metricRegistryRepository) Update(tx *sql.Tx, entry *models.MetricRegist
return lit.UpdateNamed(tx, entry, "id = :id", lit.P{"id": entry.Id})
}
+type MetricRegistrationEntry struct {
+ Name string
+ Unit string
+ MetricType string
+}
+
+func (r *metricRegistryRepository) EnsureRegisteredWithUnits(tx *sql.Tx, projectId uuid.UUID, entries []MetricRegistrationEntry) error {
+ for _, entry := range entries {
+ key := projectId.String() + ":" + entry.Name
+ if _, loaded := r.knownMetrics.Load(key); loaded {
+ continue
+ }
+
+ metricType := entry.MetricType
+ if metricType == "" {
+ metricType = defaultMetricType(entry.Name)
+ }
+ unit := entry.Unit
+ if unit == "" {
+ unit = defaultUnit(entry.Name)
+ }
+
+ rec := &models.MetricRegistry{
+ ProjectId: projectId,
+ Name: entry.Name,
+ MetricType: metricType,
+ Unit: unit,
+ Description: "",
+ CreatedAt: time.Now().UTC(),
+ }
+
+ _, err := lit.Insert[models.MetricRegistry](tx, rec)
+ if err != nil {
+ existing, findErr := r.FindByProjectAndName(tx, projectId, entry.Name)
+ if findErr != nil || existing == nil {
+ return err
+ }
+ }
+ r.knownMetrics.Store(key, true)
+ }
+ return nil
+}
+
func defaultMetricType(name string) string {
switch name {
case models.MetricNameNumGC:
diff --git a/backend/app/services/metric_registration.service.go b/backend/app/services/metric_registration.service.go
new file mode 100644
index 00000000..23b354db
--- /dev/null
+++ b/backend/app/services/metric_registration.service.go
@@ -0,0 +1,43 @@
+package services
+
+import (
+ "database/sql"
+ "fmt"
+
+ "github.com/google/uuid"
+ traceway "go.tracewayapp.com"
+
+ "github.com/tracewayapp/traceway/backend/app/db"
+ "github.com/tracewayapp/traceway/backend/app/models"
+ "github.com/tracewayapp/traceway/backend/app/repositories"
+)
+
+func CollectUniqueMetricNames(points []models.MetricPoint) []string {
+ seen := make(map[string]struct{}, len(points))
+ var names []string
+ for _, p := range points {
+ if _, ok := seen[p.Name]; !ok {
+ seen[p.Name] = struct{}{}
+ names = append(names, p.Name)
+ }
+ }
+ return names
+}
+
+func AutoRegisterMetrics(projectId uuid.UUID, names []string) {
+ _, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {
+ return struct{}{}, repositories.MetricRegistryRepository.EnsureRegistered(tx, projectId, names)
+ })
+ if err != nil {
+ traceway.CaptureException(fmt.Errorf("failed to auto-register metrics: %w", err))
+ }
+}
+
+func AutoRegisterMetricsWithUnits(projectId uuid.UUID, entries []repositories.MetricRegistrationEntry) {
+ _, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {
+ return struct{}{}, repositories.MetricRegistryRepository.EnsureRegisteredWithUnits(tx, projectId, entries)
+ })
+ if err != nil {
+ traceway.CaptureException(fmt.Errorf("failed to auto-register OTLP metrics: %w", err))
+ }
+}
diff --git a/frontend/src/app.d.ts b/frontend/src/app.d.ts
index c913bfe5..75b2d66f 100644
--- a/frontend/src/app.d.ts
+++ b/frontend/src/app.d.ts
@@ -13,6 +13,20 @@ declare global {
const __CLOUD_MODE__: string;
const __TURNSTILE_SITE_KEY__: string;
const __TRACEWAY_URL__: string;
+
+ interface Window {
+ turnstile: {
+ render: (element: HTMLElement, options: {
+ sitekey: string;
+ callback: (token: string) => void;
+ 'error-callback'?: () => void;
+ 'expired-callback'?: () => void;
+ theme?: 'light' | 'dark' | 'auto';
+ }) => string;
+ remove: (widgetId: string) => void;
+ };
+ onTurnstileLoad?: () => void;
+ }
}
export {};
diff --git a/frontend/src/lib/components/dashboard/d3-horizontal-bar-chart.svelte b/frontend/src/lib/components/dashboard/d3-horizontal-bar-chart.svelte
index 03a6a496..65dd05f0 100644
--- a/frontend/src/lib/components/dashboard/d3-horizontal-bar-chart.svelte
+++ b/frontend/src/lib/components/dashboard/d3-horizontal-bar-chart.svelte
@@ -11,7 +11,7 @@
data = [],
height = 220,
padding = { top: 10, right: 70, bottom: 10, left: 160 },
- unit = 'ms',
+ unit = '',
formatValue
} = $props<{
data: BarData[];
diff --git a/frontend/src/lib/components/dashboard/d3-line-chart.svelte b/frontend/src/lib/components/dashboard/d3-line-chart.svelte
index 12e3de77..9e59a803 100644
--- a/frontend/src/lib/components/dashboard/d3-line-chart.svelte
+++ b/frontend/src/lib/components/dashboard/d3-line-chart.svelte
@@ -4,6 +4,7 @@
import { min, max } from 'd3-array';
import { formatDateTime } from '$lib/utils/formatters';
import { getTimezone } from '$lib/state/timezone.svelte';
+ import { formatMetricValue } from '$lib/utils/metric-format';
type DataPoint = {
timestamp: Date;
@@ -124,8 +125,19 @@
// Generate Y axis ticks
const yTicks = $derived(() => yScale.ticks(4));
- // Format Y axis label
+ const yAxisUnit = $derived(() => {
+ if (!unit) return '';
+ const ticks = yTicks();
+ if (ticks.length === 0) return unit;
+ const maxTick = ticks[ticks.length - 1];
+ return formatMetricValue(maxTick, unit).unit;
+ });
+
function formatYLabel(value: number): string {
+ if (unit) {
+ const result = formatMetricValue(value, unit);
+ return result.text;
+ }
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();
@@ -463,6 +475,19 @@
</text>
{/each}
+ <!-- Y axis unit label -->
+ {#if yAxisUnit()}
+ <text
+ x={-8}
+ y={-4}
+ text-anchor="end"
+ fill="#9ca3af"
+ font-size="10"
+ >
+ {yAxisUnit()}
+ </text>
+ {/if}
+
<!-- X axis line -->
<line
x1={0}
diff --git a/frontend/src/lib/components/dashboard/metric-card.svelte b/frontend/src/lib/components/dashboard/metric-card.svelte
index 2bc7cdb4..682ede90 100644
--- a/frontend/src/lib/components/dashboard/metric-card.svelte
+++ b/frontend/src/lib/components/dashboard/metric-card.svelte
@@ -3,6 +3,7 @@
import type { DashboardMetric, MetricTrendPoint, ServerMetricTrend } from '$lib/types/dashboard';
import { min, max } from 'd3-array';
import D3LineChart from './d3-line-chart.svelte';
+ import { formatMetricLabel } from '$lib/utils/metric-format';
let {
metric,
@@ -27,36 +28,6 @@
metric.servers && metric.servers.length > 1
);
- // Smart number formatting based on unit type
- function formatMetricValue(value: number, unit: string): string {
- if (unit === '%') {
- if (value === 0) return '0';
- if (Math.abs(value) < 0.1) return value.toFixed(2);
- if (Math.abs(value) < 10) return value.toFixed(1);
- return Math.round(value).toString();
- }
-
- if (unit === 'ms') {
- if (value < 1) return (value * 1000).toFixed(0);
- if (value < 10) return value.toFixed(1);
- if (value < 1000) return Math.round(value).toString();
- return (value / 1000).toFixed(1);
- }
-
- if (unit === 'count' || unit === '') {
- if (value >= 1_000_000) return (value / 1_000_000).toFixed(1) + 'M';
- if (value >= 1_000) return (value / 1_000).toFixed(1) + 'K';
- return Math.round(value).toString();
- }
-
- if (unit === 'MB') {
- if (value >= 1024) return (value / 1024).toFixed(1) + ' GB';
- return Math.round(value).toString() + ' MB';
- }
-
- if (Number.isInteger(value)) return value.toString();
- return value.toFixed(1);
- }
// Calculate X domain from timeDomain or data
const xDomainValue = $derived(() => {
@@ -115,7 +86,7 @@
servers={metric.servers}
{serverColorMap}
unit={metric.unit}
- formatValue={(v) => metric.formatValue ? metric.formatValue(v) : formatMetricValue(v, metric.unit)}
+ formatValue={(v) => metric.formatValue ? metric.formatValue(v) : formatMetricLabel(v, metric.unit)}
{sharedHoverTime}
{isSourceChart}
{onHoverTimeChange}
diff --git a/frontend/src/lib/components/dashboard/widget-config-panel.svelte b/frontend/src/lib/components/dashboard/widget-config-panel.svelte
index 0bfb21f6..43874625 100644
--- a/frontend/src/lib/components/dashboard/widget-config-panel.svelte
+++ b/frontend/src/lib/components/dashboard/widget-config-panel.svelte
@@ -36,6 +36,8 @@
let title = $state(widget?.title ?? '');
let widgetType = $state(widget?.widgetType ?? 'line_chart');
+ let unit = $state(widget?.config?.unit ?? '');
+ let unitManuallySet = $state(!!widget?.config?.unit);
let sources = $state<WidgetSource[]>(
widget?.config?.sources ?? [{ type: 'metric', name: '', aggregation: 'avg' }]
);
@@ -44,6 +46,8 @@
if (open) {
title = widget?.title ?? '';
widgetType = widget?.widgetType ?? 'line_chart';
+ unit = widget?.config?.unit ?? '';
+ unitManuallySet = !!widget?.config?.unit;
sources = widget?.config?.sources
? [...widget.config.sources]
: [{ type: 'metric', name: '', aggregation: 'avg' }];
@@ -55,6 +59,11 @@
return m?.tagKeys ?? [];
}
+ function getMetricUnit(metricName: string): string {
+ const m = availableMetrics.find((m: DiscoveredMetric) => m.name === metricName);
+ return m?.unit ?? '';
+ }
+
async function loadTagValues(metricName: string, key: string): Promise<string[]> {
try {
const response = await api.get(
@@ -67,10 +76,18 @@
}
}
+ function handleMetricChange(index: number, value: string) {
+ sources[index].name = value;
+ if (!unitManuallySet) {
+ unit = getMetricUnit(value);
+ }
+ }
+
function handleSave() {
const validSources = sources.filter((s: WidgetSource) => s.name);
const displayTitle = title.trim() || validSources[0]?.name || '';
const config: Record<string, any> = { sources: validSources };
+ if (unit) config.unit = unit;
onSave({
title: displayTitle,
widgetType,
@@ -124,6 +141,17 @@
</Select.Root>
</div>
+ <div>
+ <label class="text-sm font-medium" for="widget-unit">Unit (optional)</label>
+ <Input
+ id="widget-unit"
+ bind:value={unit}
+ placeholder="Auto-detected from metric"
+ oninput={() => { unitManuallySet = unit.length > 0; }}
+ />
+ <p class="text-xs text-muted-foreground mt-1">%, ms, s, MB, GB, bytes, count, ns</p>
+ </div>
+
{#each sources as source, i}
<div class="space-y-2 rounded-md border p-3">
<div class="flex items-center gap-2">
@@ -131,7 +159,7 @@
type="single"
value={source.name}
onValueChange={(v) => {
- if (v) sources[i].name = v;
+ if (v) handleMetricChange(i, v);
}}
>
<Select.Trigger class="flex-1">{source.name || 'Select metric'}</Select.Trigger>
diff --git a/frontend/src/lib/components/dashboard/widget-grid.svelte b/frontend/src/lib/components/dashboard/widget-grid.svelte
index 9b6fe9ad..d6b6a5e6 100644
--- a/frontend/src/lib/components/dashboard/widget-grid.svelte
+++ b/frontend/src/lib/components/dashboard/widget-grid.svelte
@@ -66,7 +66,7 @@
<Card.Root class="h-full gap-0">
<Card.Header class="pr-2 pb-1">
<div class="flex items-center justify-between">
- <Card.Title class="text-sm font-medium">{widget.title}</Card.Title>
+ <Card.Title class="text-sm font-medium">{widget.title}{#if widget.config?.unit}<span class="text-xs font-normal text-muted-foreground"> ({widget.config.unit})</span>{/if}</Card.Title>
<DropdownMenu.Root>
<DropdownMenu.Trigger
class="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
diff --git a/frontend/src/lib/components/dashboard/widget-renderer.svelte b/frontend/src/lib/components/dashboard/widget-renderer.svelte
index 7fac2033..1a310d09 100644
--- a/frontend/src/lib/components/dashboard/widget-renderer.svelte
+++ b/frontend/src/lib/components/dashboard/widget-renderer.svelte
@@ -6,6 +6,7 @@
import { projectsState } from '$lib/state/projects.svelte';
import { LoadingCircle } from '$lib/components/ui/loading-circle';
import type { MetricTrendPoint, MetricQueryResponse } from '$lib/types/dashboard';
+ import { formatMetricLabel } from '$lib/utils/metric-format';
type WidgetSource = {
type: 'metric';
@@ -19,6 +20,7 @@
sources?: WidgetSource[];
yAxisLabel?: string;
showLegend?: boolean;
+ unit?: string;
};
let {
@@ -49,9 +51,12 @@
let series = $state<Array<{ key: string; data: MetricTrendPoint[]; color: string }>>([]);
let loading = $state(true);
let singleValue = $state<number | null>(null);
+ let resolvedUnit = $state('');
const colors = ['#3b82f6', '#ef4444', '#22c55e', '#f59e0b', '#8b5cf6', '#ec4899'];
+ const effectiveUnit = $derived(widget.config.unit ?? resolvedUnit);
+
async function loadData() {
const sources = widget.config.sources;
if (!sources || sources.length === 0) {
@@ -77,7 +82,9 @@
{ projectId: projectsState.currentProjectId ?? undefined }
);
+ const units = new Set<string>();
for (const result of response.results) {
+ if (result.unit) units.add(result.unit);
for (const [key, points] of Object.entries(result.series)) {
const label = Object.keys(result.series).length > 1 ? `${result.name} (${key})` : result.name;
newSeries.push({
@@ -92,6 +99,7 @@
}
}
+ resolvedUnit = units.size === 1 ? [...units][0] : '';
series = newSeries;
if (widget.widgetType === 'single_value' && newSeries.length > 0 && newSeries[0].data.length > 0) {
@@ -126,12 +134,12 @@
{:else if widget.widgetType === 'single_value'}
<div class="flex h-full flex-col items-center justify-center">
<span class="text-3xl font-bold">
- {singleValue !== null ? (Number.isInteger(singleValue) ? singleValue : singleValue.toFixed(2)) : '-'}
+ {singleValue !== null ? formatMetricLabel(singleValue, effectiveUnit) : '-'}
</span>
</div>
{:else if widget.widgetType === 'bar_chart'}
{#if barData.length > 0}
- <D3HorizontalBarChart data={barData} height={200} unit="" />
+ <D3HorizontalBarChart data={barData} height={200} unit={effectiveUnit} formatValue={(v) => formatMetricLabel(v, effectiveUnit)} />
{:else}
<div class="flex h-full items-center justify-center text-sm text-muted-foreground">
No data
@@ -139,7 +147,7 @@
{/if}
{:else if widget.widgetType === 'table'}
{#if series.length > 0}
- <WidgetTable {series} />
+ <WidgetTable {series} unit={effectiveUnit} />
{:else}
<div class="flex h-full items-center justify-center text-sm text-muted-foreground">
No data
@@ -155,6 +163,8 @@
{onRangeSelect}
data={series[0]?.data ?? []}
areaFill={true}
+ unit={effectiveUnit}
+ formatValue={(v) => formatMetricLabel(v, effectiveUnit)}
{sharedHoverTime}
{isSourceChart}
{onHoverTimeChange}
@@ -172,6 +182,8 @@
padding={{ top: 10, right: 4, bottom: 20, left: 45 }}
{onRangeSelect}
data={series[0]?.data ?? []}
+ unit={effectiveUnit}
+ formatValue={(v) => formatMetricLabel(v, effectiveUnit)}
{sharedHoverTime}
{isSourceChart}
{onHoverTimeChange}
diff --git a/frontend/src/lib/components/dashboard/widget-table.svelte b/frontend/src/lib/components/dashboard/widget-table.svelte
index e1e57fea..2e0e745f 100644
--- a/frontend/src/lib/components/dashboard/widget-table.svelte
+++ b/frontend/src/lib/components/dashboard/widget-table.svelte
@@ -1,14 +1,16 @@
<script lang="ts">
import * as Table from '$lib/components/ui/table';
import type { MetricTrendPoint } from '$lib/types/dashboard';
+ import { formatMetricLabel } from '$lib/utils/metric-format';
type SeriesItem = {
key: string;
data: MetricTrendPoint[];
};
- let { series = [] } = $props<{
+ let { series = [], unit = '' } = $props<{
series: SeriesItem[];
+ unit?: string;
}>();
const stats = $derived(() => {
@@ -33,6 +35,7 @@
});
function fmt(v: number): string {
+ if (unit) return formatMetricLabel(v, unit);
if (Number.isInteger(v)) return v.toString();
return v.toFixed(2);
}
diff --git a/frontend/src/lib/components/turnstile-widget.svelte b/frontend/src/lib/components/turnstile-widget.svelte
index 0c94ecb2..5e872bf0 100644
--- a/frontend/src/lib/components/turnstile-widget.svelte
+++ b/frontend/src/lib/components/turnstile-widget.svelte
@@ -13,22 +13,6 @@
let container: HTMLDivElement;
let widgetId: string | null = null;
- declare global {
- interface Window {
- turnstile: {
- render: (element: HTMLElement, options: {
- sitekey: string;
- callback: (token: string) => void;
- 'error-callback'?: () => void;
- 'expired-callback'?: () => void;
- theme?: 'light' | 'dark' | 'auto';
- }) => string;
- remove: (widgetId: string) => void;
- };
- onTurnstileLoad?: () => void;
- }
- }
-
function loadScript(): Promise<void> {
return new Promise((resolve) => {
if (window.turnstile) {
diff --git a/frontend/src/lib/types/dashboard.ts b/frontend/src/lib/types/dashboard.ts
index 4de40a36..57e7930c 100644
--- a/frontend/src/lib/types/dashboard.ts
+++ b/frontend/src/lib/types/dashboard.ts
@@ -80,6 +80,7 @@ export type TimeSeriesPoint = {
export type MetricQueryResult = {
name: string;
+ unit: string;
series: Record<string, TimeSeriesPoint[]>;
};
diff --git a/frontend/src/lib/utils/metric-format.ts b/frontend/src/lib/utils/metric-format.ts
new file mode 100644
index 00000000..de337375
--- /dev/null
+++ b/frontend/src/lib/utils/metric-format.ts
@@ -0,0 +1,66 @@
+type FormatResult = { text: string; unit: string };
+
+export function formatMetricValue(value: number, unit: string): FormatResult {
+ if (unit === '%') {
+ if (value === 0) return { text: '0', unit: '%' };
+ if (Math.abs(value) < 0.1) return { text: value.toFixed(2), unit: '%' };
+ if (Math.abs(value) < 10) return { text: value.toFixed(1), unit: '%' };
+ return { text: Math.round(value).toString(), unit: '%' };
+ }
+
+ if (unit === 'ms') {
+ if (value < 1) return { text: (value * 1000).toFixed(0), unit: 'µs' };
+ if (value < 10) return { text: value.toFixed(1), unit: 'ms' };
+ if (value < 1000) return { text: Math.round(value).toString(), unit: 'ms' };
+ return { text: (value / 1000).toFixed(1), unit: 's' };
+ }
+
+ if (unit === 'ns') {
+ if (value < 1000) return { text: Math.round(value).toString(), unit: 'ns' };
+ if (value < 1_000_000) return { text: (value / 1000).toFixed(1), unit: 'µs' };
+ if (value < 1_000_000_000) return { text: (value / 1_000_000).toFixed(1), unit: 'ms' };
+ return { text: (value / 1_000_000_000).toFixed(1), unit: 's' };
+ }
+
+ if (unit === 's') {
+ if (value < 0.001) return { text: (value * 1_000_000).toFixed(0), unit: 'µs' };
+ if (value < 1) return { text: (value * 1000).toFixed(1), unit: 'ms' };
+ if (value < 60) return { text: value.toFixed(1), unit: 's' };
+ if (value < 3600) return { text: (value / 60).toFixed(1), unit: 'min' };
+ return { text: (value / 3600).toFixed(1), unit: 'h' };
+ }
+
+ if (unit === 'MB') {
+ if (value < 1) return { text: (value * 1024).toFixed(0), unit: 'KB' };
+ if (value >= 1024) return { text: (value / 1024).toFixed(1), unit: 'GB' };
+ return { text: Math.round(value).toString(), unit: 'MB' };
+ }
+
+ if (unit === 'GB') {
+ if (value < 1) return { text: (value * 1024).toFixed(0), unit: 'MB' };
+ if (value >= 1024) return { text: (value / 1024).toFixed(1), unit: 'TB' };
+ return { text: value.toFixed(1), unit: 'GB' };
+ }
+
+ if (unit === 'bytes' || unit === 'B') {
+ if (value < 1024) return { text: Math.round(value).toString(), unit: 'B' };
+ if (value < 1024 * 1024) return { text: (value / 1024).toFixed(1), unit: 'KB' };
+ if (value < 1024 * 1024 * 1024) return { text: (value / (1024 * 1024)).toFixed(1), unit: 'MB' };
+ return { text: (value / (1024 * 1024 * 1024)).toFixed(1), unit: 'GB' };
+ }
+
+ if (unit === 'count' || unit === '') {
+ if (value >= 1_000_000) return { text: (value / 1_000_000).toFixed(1), unit: 'M' };
+ if (value >= 1_000) return { text: (value / 1_000).toFixed(1), unit: 'K' };
+ return { text: Math.round(value).toString(), unit: '' };
+ }
+
+ if (Number.isInteger(value)) return { text: value.toString(), unit };
+ return { text: value.toFixed(1), unit };
+}
+
+export function formatMetricLabel(value: number, unit: string): string {
+ const result = formatMetricValue(value, unit);
+ if (!result.unit) return result.text;
+ return `${result.text} ${result.unit}`;
+}
diff --git a/testing/devtesting-symfony/src/Controller/TestController.php b/testing/devtesting-symfony/src/Controller/TestController.php
index d68f9791..2ec17130 100644
--- a/testing/devtesting-symfony/src/Controller/TestController.php
+++ b/testing/devtesting-symfony/src/Controller/TestController.php
@@ -99,9 +99,31 @@ class TestController
'operation' => $operations[array_rand($operations)],
]);
+ $hosts = ['web-01', 'web-02', 'web-03'];
+ $cpuUsage = 10.0 + (random_int(0, 8500) / 100.0);
+
+ $cpuGauge = $meter->createObservableGauge('app.cpu_usage', '%', 'CPU usage percentage');
+ $cpuGauge->observe(function ($observer) use ($cpuUsage, $hosts) {
+ $observer->observe($cpuUsage, [
+ 'host' => $hosts[array_rand($hosts)],
+ ]);
+ });
+
+ $methods = ['GET', 'POST'];
+ $statuses = ['200', '404', '500'];
+ $requestCount = random_int(1, 50);
+
+ $counter = $meter->createCounter('app.requests_total', 'requests', 'Total HTTP requests');
+ $counter->add($requestCount, [
+ 'method' => $methods[array_rand($methods)],
+ 'status' => $statuses[array_rand($statuses)],
+ ]);
+
return new JsonResponse([
'queue_size' => $queueSize,
'cache_latency_ms' => $latency,
+ 'cpu_usage' => $cpuUsage,
+ 'requests_total' => $requestCount,
]);
}