Skip to content

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

feat: streaming endpoints impact calculations (#160)

narrow-adventured20fec8c0637
diff --git a/backend/app/controllers/otelcontrollers/helpers.go b/backend/app/controllers/otelcontrollers/helpers.go
index 2367b420..04cc40d6 100644
--- a/backend/app/controllers/otelcontrollers/helpers.go
+++ b/backend/app/controllers/otelcontrollers/helpers.go
@@ -131,3 +131,34 @@ func getFloatAttribute(attrs []*commonpb.KeyValue, key string) float64 {
}
return 0
}
+
+// getStringValues returns all string values for an attribute. Handles both
+// scalar string (`AnyValue_StringValue`) and the array form OTel uses for
+// captured response headers (`AnyValue_ArrayValue` of `AnyValue_StringValue`).
+func getStringValues(attrs []*commonpb.KeyValue, key string) []string {
+ var out []string
+ for _, kv := range attrs {
+ if kv.Key != key || kv.Value == nil {
+ continue
+ }
+ switch v := kv.Value.Value.(type) {
+ case *commonpb.AnyValue_StringValue:
+ if v.StringValue != "" {
+ out = append(out, v.StringValue)
+ }
+ case *commonpb.AnyValue_ArrayValue:
+ if v.ArrayValue == nil {
+ continue
+ }
+ for _, item := range v.ArrayValue.Values {
+ if item == nil {
+ continue
+ }
+ if sv, ok := item.Value.(*commonpb.AnyValue_StringValue); ok && sv.StringValue != "" {
+ out = append(out, sv.StringValue)
+ }
+ }
+ }
+ }
+ return out
+}
diff --git a/backend/app/controllers/otelcontrollers/trace_converter.go b/backend/app/controllers/otelcontrollers/trace_converter.go
index 1cf3263d..dc540825 100644
--- a/backend/app/controllers/otelcontrollers/trace_converter.go
+++ b/backend/app/controllers/otelcontrollers/trace_converter.go
@@ -3,6 +3,7 @@ package otelcontrollers
import (
"encoding/json"
"fmt"
+ "net/http"
"strings"
"time"
@@ -235,9 +236,44 @@ func buildEndpoint(
Attributes: allAttrs,
AppVersion: appVersion,
ServerName: serverName,
+ IsStream: isOtelStreamingEndpoint(attrs, statusCode),
}
}
+// isOtelStreamingEndpoint detects long-lived streaming responses on OTel spans:
+// - status 101 (WebSocket upgrade)
+// - http.response.header.content-type contains text/event-stream (SSE)
+//
+// OTel has no standard `is_stream` attribute, so we sniff the captured headers.
+// Clients that don't capture `http.response.header.content-type` won't trigger
+// SSE detection — they can fall back to a vendor extension attribute
+// `traceway.is_stream` (boolean) or the WebSocket signal.
+func isOtelStreamingEndpoint(attrs []*commonpb.KeyValue, statusCode int16) bool {
+ if statusCode == http.StatusSwitchingProtocols {
+ return true
+ }
+ if b, ok := getBoolAttribute(attrs, "traceway.is_stream"); ok && b {
+ return true
+ }
+ for _, ct := range getStringValues(attrs, "http.response.header.content-type") {
+ if strings.HasPrefix(strings.ToLower(strings.TrimSpace(ct)), "text/event-stream") {
+ return true
+ }
+ }
+ return false
+}
+
+func getBoolAttribute(attrs []*commonpb.KeyValue, key string) (bool, bool) {
+ for _, kv := range attrs {
+ if kv.Key == key && kv.Value != nil {
+ if bv, ok := kv.Value.Value.(*commonpb.AnyValue_BoolValue); ok {
+ return bv.BoolValue, true
+ }
+ }
+ }
+ return false, false
+}
+
func getHTTPEndpoint(attrs []*commonpb.KeyValue, fallback string) string {
method := getStringAttribute(attrs, "http.request.method")
if method == "" {
diff --git a/backend/app/migrations/ch/0057_add_is_stream_to_endpoints.up.sql b/backend/app/migrations/ch/0057_add_is_stream_to_endpoints.up.sql
new file mode 100644
index 00000000..6f2b9479
--- /dev/null
+++ b/backend/app/migrations/ch/0057_add_is_stream_to_endpoints.up.sql
@@ -0,0 +1 @@
+ALTER TABLE endpoints ADD COLUMN is_stream UInt8 DEFAULT 0
diff --git a/backend/app/migrations/sqlite_telemetry/0008_add_is_stream_to_endpoints.up.sql b/backend/app/migrations/sqlite_telemetry/0008_add_is_stream_to_endpoints.up.sql
new file mode 100644
index 00000000..6a5ac120
--- /dev/null
+++ b/backend/app/migrations/sqlite_telemetry/0008_add_is_stream_to_endpoints.up.sql
@@ -0,0 +1 @@
+ALTER TABLE endpoints ADD COLUMN is_stream INTEGER NOT NULL DEFAULT 0
diff --git a/backend/app/models/clientmodels/clientmodels.model.go b/backend/app/models/clientmodels/clientmodels.model.go
index 966e98f4..9d2ad617 100644
--- a/backend/app/models/clientmodels/clientmodels.model.go
+++ b/backend/app/models/clientmodels/clientmodels.model.go
@@ -99,6 +99,8 @@ type ClientTrace struct {
DistributedTraceId string `json:"distributedTraceId"`
}
+const streamAttributeKey = "traceway.is_stream"
+
// ParsedId returns the trace ID as uuid.UUID
func (c *ClientTrace) ParsedId() uuid.UUID {
if parsed, err := uuid.Parse(c.Id); err == nil {
@@ -130,6 +132,7 @@ func (c *ClientTrace) ToEndpoint(appVersion, serverName string) models.Endpoint
AppVersion: appVersion,
ServerName: serverName,
DistributedTraceId: c.parsedDistributedTraceId(),
+ IsStream: c.Attributes[streamAttributeKey] == "true",
}
}
diff --git a/backend/app/models/endpoint.model.go b/backend/app/models/endpoint.model.go
index 566bc359..5f634f52 100644
--- a/backend/app/models/endpoint.model.go
+++ b/backend/app/models/endpoint.model.go
@@ -21,6 +21,7 @@ type Endpoint struct {
ServerName string `json:"serverName" ch:"server_name"`
DistributedTraceId *uuid.UUID `json:"distributedTraceId,omitempty" ch:"distributed_trace_id"`
SpanId *uuid.UUID `json:"spanId,omitempty" ch:"span_id"`
+ IsStream bool `json:"isStream" ch:"is_stream"`
}
type EndpointStats struct {
@@ -33,6 +34,7 @@ type EndpointStats struct {
LastSeen time.Time `json:"lastSeen"`
Impact float64 `json:"impact"` // 0-1 impact score
ImpactReason string `json:"impactReason"` // human-readable explanation of the dominant impact factor
+ IsStream bool `json:"isStream"` // true => latency/Apdex/impact intentionally zero
}
// EndpointDetailStats contains detailed statistics for a specific endpoint
@@ -45,6 +47,7 @@ type EndpointDetailStats struct {
Apdex float64 `json:"apdex"` // 0-1 score
ErrorRate float64 `json:"errorRate"` // percentage
Throughput float64 `json:"throughput"` // requests per minute
+ IsStream bool `json:"isStream"` // true => latency/Apdex are not meaningful for this endpoint
}
// EndpointTimeSeriesPoint represents a single data point in a time series for endpoint charts
diff --git a/backend/app/repositories/endpoint.repository.go b/backend/app/repositories/endpoint.repository.go
index 8efb7b3b..93f1de61 100644
--- a/backend/app/repositories/endpoint.repository.go
+++ b/backend/app/repositories/endpoint.repository.go
@@ -18,7 +18,7 @@ import (
type endpointRepository struct{}
func (e *endpointRepository) InsertAsync(ctx context.Context, lines []models.Endpoint) error {
- batch, err := chdb.Conn.PrepareBatch(clickhouse.Context(context.Background(), clickhouse.WithAsync(false)), "INSERT INTO endpoints (id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, distributed_trace_id, span_id)")
+ batch, err := chdb.Conn.PrepareBatch(clickhouse.Context(context.Background(), clickhouse.WithAsync(false)), "INSERT INTO endpoints (id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, distributed_trace_id, span_id, is_stream)")
if err != nil {
return err
}
@@ -29,7 +29,11 @@ func (e *endpointRepository) InsertAsync(ctx context.Context, lines []models.End
attributesJSON = string(attributesBytes)
}
}
- if err := batch.Append(t.Id, t.ProjectId, t.Endpoint, int64(t.Duration), t.RecordedAt, t.StatusCode, t.BodySize, t.ClientIP, attributesJSON, t.AppVersion, t.ServerName, t.DistributedTraceId, t.SpanId); err != nil {
+ isStream := uint8(0)
+ if t.IsStream {
+ isStream = 1
+ }
+ if err := batch.Append(t.Id, t.ProjectId, t.Endpoint, int64(t.Duration), t.RecordedAt, t.StatusCode, t.BodySize, t.ClientIP, attributesJSON, t.AppVersion, t.ServerName, t.DistributedTraceId, t.SpanId, isStream); err != nil {
return err
}
}
@@ -136,7 +140,34 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectI
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(
+ server_error_count, is_stream,
+ if(is_stream = 1,
+ -- Streaming endpoints: skip Apdex + P99 (duration-driven, meaningless
+ -- for connection lifetimes). Substitute server_error_count for
+ -- bad_count so a 30s SSE connection isn't classified as "bad" by
+ -- duration. Keeps components 2, 4, 5 of the normal impact formula.
+ greatest(
+ multiIf(
+ server_error_count / total_count > 0.33, 0.75,
+ server_error_count / total_count > 0.20, 0.50,
+ server_error_count / total_count > 0.10, 0.25, 0.0),
+ if(endpoint != 'UNMATCHED' AND total_count > 10,
+ multiIf(
+ client_error_count / total_count > 0.50, 0.75,
+ client_error_count / total_count > 0.25, 0.50, 0.0),
+ 0.0),
+ multiIf(
+ server_error_count / total_count > 0.10 AND server_error_count >= 500, 0.75,
+ server_error_count / total_count > 0.10 AND server_error_count >= 50, 0.50,
+ server_error_count / total_count > 0.05 AND server_error_count >= 2000, 0.75,
+ server_error_count / total_count > 0.05 AND server_error_count >= 500, 0.50,
+ server_error_count / total_count > 0.05 AND server_error_count >= 50, 0.25,
+ server_error_count / total_count > 0.01 AND server_error_count >= 10000, 0.75,
+ server_error_count / total_count > 0.01 AND server_error_count >= 2000, 0.50,
+ server_error_count / total_count > 0.01 AND server_error_count >= 500, 0.25,
+ 0.0)
+ ),
+ greatest(
if(total_count > 0,
1.0 - ((satisfied_count + tolerating_count * 0.5) / total_count), 0.0),
multiIf(
@@ -162,11 +193,12 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectI
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
+ )) as impact
FROM (
SELECT
endpoint,
offset_ms,
+ is_stream,
count() as total_count,
quantile(0.5)(duration) as p50_duration,
quantile(0.95)(duration) as p95_duration,
@@ -180,16 +212,17 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectI
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
+ countIf(status_code >= 400 AND status_code < 500) as client_error_count,
+ countIf(status_code >= 500) as server_error_count
FROM (
- SELECT e.endpoint, e.duration, e.status_code, e.recorded_at,
+ SELECT e.endpoint, e.duration, e.status_code, e.recorded_at, e.is_stream,
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
+ GROUP BY endpoint, offset_ms, is_stream
)
ORDER BY ` + orderExpr + ` ` + sortDir + `
LIMIT ? OFFSET ?`
@@ -208,12 +241,22 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectI
var s models.EndpointStats
var p50, p95, p99, avg float64
var offsetMs uint32
- var satisfiedCount, toleratingCount, badCount, clientErrorCount uint64
+ var satisfiedCount, toleratingCount, badCount, clientErrorCount, serverErrorCount uint64
+ var isStream uint8
if err := rows.Scan(&s.Endpoint, &s.Count, &p50, &p95, &p99, &avg, &s.LastSeen,
&offsetMs, &satisfiedCount, &toleratingCount, &badCount, &clientErrorCount,
- &s.Impact); err != nil {
+ &serverErrorCount, &isStream, &s.Impact); err != nil {
return nil, 0, err
}
+ s.IsStream = isStream == 1
+ if s.IsStream {
+ // Latency/Apdex are zero for streams. Impact came from the
+ // stream-specific branch of the SQL (status-code components only);
+ // the reason is computed from the same status-code aggregates.
+ s.ImpactReason = ComputeStreamImpactReason(s.Endpoint, s.Count, serverErrorCount, clientErrorCount)
+ stats = append(stats, s)
+ continue
+ }
s.P50Duration = time.Duration(p50)
s.P95Duration = time.Duration(p95)
s.P99Duration = time.Duration(p99)
@@ -340,7 +383,7 @@ func (e *endpointRepository) AvgDurationByHour(ctx context.Context, projectId uu
toStartOfHour(recorded_at) as hour,
avg(duration) / 1000000 as avg_duration_ms
FROM endpoints
- WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? AND is_stream = 0
GROUP BY hour
ORDER BY hour ASC`
@@ -424,7 +467,7 @@ func (e *endpointRepository) AvgDurationByInterval(ctx context.Context, projectI
toStartOfInterval(recorded_at, INTERVAL ? MINUTE) as bucket,
avg(duration) / 1000000 as avg_duration_ms
FROM endpoints
- WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? AND is_stream = 0
GROUP BY bucket
ORDER BY bucket ASC`
@@ -530,7 +573,7 @@ func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId u
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 <= ?
+ WHERE e.project_id = ? AND e.recorded_at >= ? AND e.recorded_at <= ? AND e.is_stream = 0
)
GROUP BY endpoint, offset_ms
)
@@ -575,21 +618,25 @@ func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId uui
query := `SELECT
count() as count,
- if(count() > 0, avg(duration) / 1000000, 0) as avg_duration_ms,
- if(count() > 0, quantile(0.5)(duration) / 1000000, 0) as p50_duration_ms,
- if(count() > 0, quantile(0.95)(duration) / 1000000, 0) as p95_duration_ms,
- if(count() > 0, quantile(0.99)(duration) / 1000000, 0) as p99_duration_ms,
+ if(count() > 0, avg(if(is_stream = 0, duration, NULL)) / 1000000, 0) as avg_duration_ms,
+ if(count() > 0, quantile(0.5)(if(is_stream = 0, duration, NULL)) / 1000000, 0) as p50_duration_ms,
+ if(count() > 0, quantile(0.95)(if(is_stream = 0, duration, NULL)) / 1000000, 0) as p95_duration_ms,
+ if(count() > 0, quantile(0.99)(if(is_stream = 0, duration, NULL)) / 1000000, 0) as p99_duration_ms,
if(count() > 0, countIf(status_code >= 500) * 100.0 / count(), 0) as error_rate,
if(count() > 0,
- countIf(duration <= 500000000 AND status_code < 500) +
- (countIf(duration > 500000000 AND duration <= 2000000000 AND status_code < 500) * 0.5),
- 0) as satisfied_tolerating
+ countIf(duration <= 500000000 AND status_code < 500 AND is_stream = 0) +
+ (countIf(duration > 500000000 AND duration <= 2000000000 AND status_code < 500 AND is_stream = 0) * 0.5),
+ 0) as satisfied_tolerating,
+ max(is_stream) as is_stream,
+ countIf(is_stream = 0) as non_stream_count
FROM endpoints
WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?`
var stats models.EndpointDetailStats
var count uint64
var satisfiedTolerating float64
+ var isStream uint8
+ var nonStreamCount uint64
err := chdb.Conn.QueryRow(ctx, query, projectId, endpoint, start, end).Scan(
&count,
@@ -599,52 +646,63 @@ func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId uui
&stats.P99Duration,
&stats.ErrorRate,
&satisfiedTolerating,
+ &isStream,
+ &nonStreamCount,
)
if err != nil {
return nil, err
}
stats.Count = int64(count)
- // Calculate Apdex: (satisfied + tolerating*0.5) / total
- if count > 0 {
- stats.Apdex = satisfiedTolerating / float64(count)
+ stats.IsStream = isStream == 1
+ // Apdex is the share of non-stream requests in the satisfied/tolerating bucket.
+ if !stats.IsStream && nonStreamCount > 0 {
+ stats.Apdex = satisfiedTolerating / float64(nonStreamCount)
}
// Calculate throughput (requests per minute)
stats.Throughput = float64(count) / durationMinutes
+ if stats.IsStream {
+ stats.AvgDuration = 0
+ stats.MedianDuration = 0
+ stats.P95Duration = 0
+ stats.P99Duration = 0
+ stats.Apdex = 0
+ }
+
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
+ // Step 1: Get top 5 endpoints ranked by selected metric (streams excluded)
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 <= ?
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? AND is_stream = 0
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 <= ?
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? AND is_stream = 0
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 <= ?
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? AND is_stream = 0
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 <= ?
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? AND is_stream = 0
GROUP BY endpoint
ORDER BY metric_value DESC
LIMIT 5`
@@ -700,7 +758,7 @@ func (e *endpointRepository) GetEndpointStackedChart(ctx context.Context, projec
` + caseExpr + ` as endpoint_category,
` + metricExpr + ` as metric_value
FROM endpoints
- WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? AND is_stream = 0
GROUP BY bucket, endpoint_category
ORDER BY bucket ASC, endpoint_category ASC`
diff --git a/backend/app/repositories/endpoint.repository_sqlite.go b/backend/app/repositories/endpoint.repository_sqlite.go
index 41865393..8767aba5 100644
--- a/backend/app/repositories/endpoint.repository_sqlite.go
+++ b/backend/app/repositories/endpoint.repository_sqlite.go
@@ -31,6 +31,7 @@ type endpoint struct {
ServerName string `lit:"server_name"`
DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`
SpanId *uuid.UUID `lit:"span_id"`
+ IsStream bool `lit:"is_stream"`
}
type groupedEndpointRow struct {
@@ -44,6 +45,7 @@ type groupedEndpointRow struct {
SatisfiedCount uint64 `lit:"satisfied_count"`
ToleratingCount uint64 `lit:"tolerating_count"`
BadCount uint64 `lit:"bad_count"`
+ IsStream bool `lit:"is_stream"`
}
type endpointDurationRow struct {
@@ -71,6 +73,10 @@ type endpointDetailStatsRow struct {
SatisfiedTolerating float64 `lit:"satisfied_tolerating"`
}
+type isStreamFlagRow struct {
+ IsStream bool `lit:"is_stream"`
+}
+
func init() {
models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {
lit.RegisterModel[endpoint](driver)
@@ -80,6 +86,7 @@ func init() {
lit.RegisterModel[endpointMetricRow](driver)
lit.RegisterModel[distinctEndpointRow](driver)
lit.RegisterModel[endpointDetailStatsRow](driver)
+ lit.RegisterModel[isStreamFlagRow](driver)
})
}
@@ -98,6 +105,7 @@ func endpointToRow(e models.Endpoint) endpoint {
ServerName: e.ServerName,
DistributedTraceId: e.DistributedTraceId,
SpanId: e.SpanId,
+ IsStream: e.IsStream,
}
}
@@ -115,6 +123,7 @@ func (r *endpoint) toModel() models.Endpoint {
ServerName: r.ServerName,
DistributedTraceId: r.DistributedTraceId,
SpanId: r.SpanId,
+ IsStream: r.IsStream,
}
if r.Attributes != nil {
e.Attributes = map[string]string(r.Attributes)
@@ -219,7 +228,8 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectI
SUM(CASE WHEN e.status_code >= 400 AND e.status_code < 500 THEN 1 ELSE 0 END) as client_error_count,
SUM(CASE WHEN e.duration <= (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) as satisfied_count,
SUM(CASE WHEN e.duration > (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.duration <= (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) as tolerating_count,
- SUM(CASE WHEN e.duration > (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) OR e.status_code >= 500 THEN 1 ELSE 0 END) as bad_count
+ SUM(CASE WHEN e.duration > (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) OR e.status_code >= 500 THEN 1 ELSE 0 END) as bad_count,
+ MAX(e.is_stream) as is_stream
FROM endpoints e
LEFT JOIN slow_endpoints s ON e.endpoint = s.endpoint AND e.project_id = s.project_id
WHERE ` + whereClause + `
@@ -241,7 +251,7 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectI
var g groupedEndpointRow
if err := sqlRows.Scan(&g.Endpoint, &g.TotalCount, &g.AvgDuration, &g.LastSeen,
&g.OffsetMs, &g.ServerErrorCount, &g.ClientErrorCount,
- &g.SatisfiedCount, &g.ToleratingCount, &g.BadCount); err != nil {
+ &g.SatisfiedCount, &g.ToleratingCount, &g.BadCount, &g.IsStream); err != nil {
return nil, 0, err
}
groups = append(groups, g)
@@ -249,6 +259,25 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectI
var stats []models.EndpointStats
for _, g := range groups {
+ lastSeen, _ := time.Parse(time.RFC3339Nano, g.LastSeen)
+
+ // Streaming endpoints are still surfaced (count, error rate, throughput),
+ // but their connection lifetime is not request latency — zero out the
+ // latency signals. Impact still fires on status-code-driven components
+ // (server-error rate, client-error rate, volume-weighted error rate)
+ // so a streaming endpoint returning lots of 5xx still ranks.
+ if g.IsStream {
+ stats = append(stats, models.EndpointStats{
+ Endpoint: g.Endpoint,
+ Count: g.TotalCount,
+ LastSeen: lastSeen,
+ Impact: ComputeStreamImpact(g.Endpoint, g.TotalCount, g.ServerErrorCount, g.ClientErrorCount),
+ ImpactReason: ComputeStreamImpactReason(g.Endpoint, g.TotalCount, g.ServerErrorCount, g.ClientErrorCount),
+ IsStream: true,
+ })
+ continue
+ }
+
durations, err := fetchSortedDurations(ctx, projectId, g.Endpoint, fromDate, toDate)
if err != nil {
return nil, 0, err
@@ -260,8 +289,6 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectI
impact := computeImpactScore(g.Endpoint, g.TotalCount, g.SatisfiedCount, g.ToleratingCount, g.BadCount, g.ClientErrorCount, p99, g.OffsetMs)
- lastSeen, _ := time.Parse(time.RFC3339Nano, g.LastSeen)
-
stats = append(stats, models.EndpointStats{
Endpoint: g.Endpoint,
Count: g.TotalCount,
@@ -363,7 +390,7 @@ func (e *endpointRepository) CountByHour(ctx context.Context, projectId uuid.UUI
func (e *endpointRepository) AvgDurationByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {
results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,
`SELECT strftime('%Y-%m-%d %H:00:00', recorded_at) as bucket, AVG(duration) / 1000000.0 as agg_value
- FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to
+ FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0
GROUP BY bucket ORDER BY bucket ASC`,
lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})
if err != nil {
@@ -402,7 +429,7 @@ func (e *endpointRepository) AvgDurationByInterval(ctx context.Context, projectI
secs := intervalMinutes * 60
results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,
fmt.Sprintf(`SELECT datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') as bucket, AVG(duration) / 1000000.0 as agg_value
- FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to
+ FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0
GROUP BY bucket ORDER BY bucket ASC`, secs, secs),
lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})
if err != nil {
@@ -438,10 +465,11 @@ func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId u
SUM(CASE WHEN e.status_code >= 400 AND e.status_code < 500 THEN 1 ELSE 0 END) as client_error_count,
SUM(CASE WHEN e.duration <= (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) as satisfied_count,
SUM(CASE WHEN e.duration > (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.duration <= (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) as tolerating_count,
- SUM(CASE WHEN e.duration > (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) OR e.status_code >= 500 THEN 1 ELSE 0 END) as bad_count
+ SUM(CASE WHEN e.duration > (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) OR e.status_code >= 500 THEN 1 ELSE 0 END) as bad_count,
+ MAX(e.is_stream) as is_stream
FROM endpoints e
LEFT JOIN slow_endpoints s ON e.endpoint = s.endpoint AND e.project_id = s.project_id
- WHERE e.project_id = :project_id AND e.recorded_at >= :from AND e.recorded_at <= :to
+ WHERE e.project_id = :project_id AND e.recorded_at >= :from AND e.recorded_at <= :to AND e.is_stream = 0
GROUP BY e.endpoint`
parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, groupQuery, params)
@@ -460,7 +488,7 @@ func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId u
var g groupedEndpointRow
if err := sqlRows.Scan(&g.Endpoint, &g.TotalCount, &g.AvgDuration, &g.LastSeen,
&g.OffsetMs, &g.ServerErrorCount, &g.ClientErrorCount,
- &g.SatisfiedCount, &g.ToleratingCount, &g.BadCount); err != nil {
+ &g.SatisfiedCount, &g.ToleratingCount, &g.BadCount, &g.IsStream); err != nil {
return nil, err
}
groups = append(groups, g)
@@ -530,24 +558,36 @@ func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId uui
return &models.EndpointDetailStats{}, nil
}
+ isStreamRow, err := lit.SelectSingleNamed[isStreamFlagRow](db.TelemetryDB,
+ `SELECT MAX(is_stream) as is_stream FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to`,
+ params)
+ if err != nil {
+ return nil, err
+ }
+ isStream := isStreamRow != nil && isStreamRow.IsStream
+
var stats models.EndpointDetailStats
stats.Count = row.Count
- stats.AvgDuration = row.AvgDurationMs
stats.ErrorRate = row.ErrorRate
- if row.Count > 0 {
- stats.Apdex = row.SatisfiedTolerating / float64(row.Count)
- }
stats.Throughput = float64(row.Count) / durationMinutes
+ stats.IsStream = isStream
- durations, err := fetchSortedDurations(ctx, projectId, endpoint, start, end)
- if err != nil {
- return nil, err
- }
+ if !isStream {
+ stats.AvgDuration = row.AvgDurationMs
+ if row.Count > 0 {
+ stats.Apdex = row.SatisfiedTolerating / float64(row.Count)
+ }
+
+ durations, err := fetchSortedDurations(ctx, projectId, endpoint, start, end)
+ if err != nil {
+ return nil, err
+ }
- if len(durations) > 0 {
- stats.MedianDuration = computePercentile(durations, 0.5) / 1000000.0
- stats.P95Duration = computePercentile(durations, 0.95) / 1000000.0
- stats.P99Duration = computePercentile(durations, 0.99) / 1000000.0
+ if len(durations) > 0 {
+ stats.MedianDuration = computePercentile(durations, 0.5) / 1000000.0
+ stats.P95Duration = computePercentile(durations, 0.95) / 1000000.0
+ stats.P99Duration = computePercentile(durations, 0.99) / 1000000.0
+ }
}
return &stats, nil
@@ -595,7 +635,7 @@ func (e *endpointRepository) GetEndpointStackedChart(ctx context.Context, projec
%s as endpoint_category,
%s as metric_value
FROM endpoints
- WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to
+ WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0
GROUP BY bucket, endpoint_category
ORDER BY bucket ASC, endpoint_category ASC`, secs, secs, caseExpr, metricExpr)
@@ -657,7 +697,7 @@ func (e *endpointRepository) getStackedChartWithPercentiles(ctx context.Context,
endpoint,
duration
FROM endpoints
- WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to
+ WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0
ORDER BY bucket ASC, endpoint ASC, duration ASC`, bucketSecs, bucketSecs)
parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, query,
@@ -759,7 +799,7 @@ func (e *endpointRepository) UpsertSlowEndpoint(ctx context.Context, projectId u
func fetchSortedDurations(ctx context.Context, projectId uuid.UUID, endpoint string, from, to time.Time) ([]float64, error) {
results, err := lit.SelectNamed[endpointDurationRow](db.TelemetryDB,
- "SELECT duration FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to ORDER BY duration ASC",
+ "SELECT duration FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0 ORDER BY duration ASC",
lit.P{"project_id": projectId, "endpoint": endpoint, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)})
if err != nil {
return nil, err
@@ -873,7 +913,7 @@ func getTopEndpointsByMetric(ctx context.Context, projectId uuid.UUID, from, to
if metricType == "total_time" {
results, err := lit.SelectNamed[endpointMetricRow](db.TelemetryDB,
`SELECT endpoint, COUNT(*) * AVG(duration) / 1000000.0 as metric_value
- FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to
+ FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0
GROUP BY endpoint ORDER BY metric_value DESC LIMIT 5`,
params)
if err != nil {
@@ -896,7 +936,7 @@ func getTopEndpointsByMetric(ctx context.Context, projectId uuid.UUID, from, to
}
epRows, err := lit.SelectNamed[distinctEndpointRow](db.TelemetryDB,
- `SELECT DISTINCT endpoint FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to`,
+ `SELECT DISTINCT endpoint FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0`,
params)
if err != nil {
return nil, err
diff --git a/backend/app/repositories/impact.go b/backend/app/repositories/impact.go
index 7c38970d..7348c46b 100644
--- a/backend/app/repositories/impact.go
+++ b/backend/app/repositories/impact.go
@@ -103,6 +103,101 @@ func ComputeImpactReason(
}
}
+func ComputeStreamImpact(endpoint string, total, serverErrorCount, clientErrorCount uint64) float64 {
+ if total == 0 {
+ return 0
+ }
+ badRate := float64(serverErrorCount) / float64(total)
+ clientRate := float64(clientErrorCount) / float64(total)
+ return math.Max(
+ errorRateFloor(badRate),
+ math.Max(
+ clientErrorFloor(endpoint, total, clientRate),
+ volumeAwareErrorFloor(badRate, serverErrorCount),
+ ),
+ )
+}
+
+func ComputeStreamImpactReason(endpoint string, total, serverErrorCount, clientErrorCount uint64) string {
+ if total == 0 {
+ return "Streaming endpoint is healthy"
+ }
+
+ totalF := float64(total)
+ badRate := float64(serverErrorCount) / totalF
+ clientRate := float64(clientErrorCount) / totalF
+
+ errorRateScore := errorRateFloor(badRate)
+ clientErrorScore := clientErrorFloor(endpoint, total, clientRate)
+ volumeScore := volumeAwareErrorFloor(badRate, serverErrorCount)
+
+ maxScore := math.Max(errorRateScore, math.Max(clientErrorScore, volumeScore))
+ if maxScore < 0.25 {
+ return "Streaming endpoint is healthy"
+ }
+
+ // Priority when tied: Volume > Client Error > Error Rate (matches the
+ // non-stream ordering, just with the latency tiers omitted).
+ switch {
+ case volumeScore >= maxScore:
+ return fmt.Sprintf("%s server errors with %.1f%% error rate", formatCount(serverErrorCount), badRate*100)
+ case clientErrorScore >= maxScore:
+ return fmt.Sprintf("%.0f%% of stream requests returning 4xx errors", clientRate*100)
+ default:
+ return fmt.Sprintf("%.0f%% of stream requests returning 5xx errors", badRate*100)
+ }
+}
+
+// errorRateFloor / clientErrorFloor / volumeAwareErrorFloor are the tier
+// definitions from ComputeImpactReason (mirrored in computeImpactScore),
+// factored out so the stream variants reuse identical thresholds.
+func errorRateFloor(badRate float64) float64 {
+ switch {
+ case badRate > 0.33:
+ return 0.75
+ case badRate > 0.20:
+ return 0.50
+ case badRate > 0.10:
+ return 0.25
+ }
+ return 0
+}
+
+func clientErrorFloor(endpoint string, total uint64, clientRate float64) float64 {
+ if endpoint == "UNMATCHED" || total <= 10 {
+ return 0
+ }
+ switch {
+ case clientRate > 0.50:
+ return 0.75
+ case clientRate > 0.25:
+ return 0.50
+ }
+ return 0
+}
+
+func volumeAwareErrorFloor(badRate float64, badCount uint64) float64 {
+ switch {
+ case badRate > 0.10 && badCount >= 500:
+ return 0.75
+ case badRate > 0.10 && badCount >= 50:
+ return 0.50
+ case badRate > 0.05 && badCount >= 2000:
+ return 0.75
+ case badRate > 0.05 && badCount >= 500:
+ return 0.50
+ case badRate > 0.05 && badCount >= 50:
+ return 0.25
+ case badRate > 0.01 && badCount >= 10000:
+ return 0.75
+ case badRate > 0.01 && badCount >= 2000:
+ return 0.50
+ case badRate > 0.01 && badCount >= 500:
+ return 0.25
+ }
+ return 0
+}
+
func formatDurationHuman(d time.Duration) string {
if d >= time.Second {
secs := d.Seconds()
diff --git a/backend/app/repositories/testhelper_sqlite_test.go b/backend/app/repositories/testhelper_sqlite_test.go
index e13ba115..a77ab8dd 100644
--- a/backend/app/repositories/testhelper_sqlite_test.go
+++ b/backend/app/repositories/testhelper_sqlite_test.go
@@ -66,7 +66,8 @@ CREATE TABLE IF NOT EXISTS endpoints (
attributes TEXT NOT NULL DEFAULT '{}',
app_version TEXT NOT NULL DEFAULT '',
server_name TEXT NOT NULL DEFAULT '',
- distributed_trace_id TEXT DEFAULT NULL
+ distributed_trace_id TEXT DEFAULT NULL,
+ is_stream INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_endpoints_project_recorded ON endpoints(project_id, recorded_at);
CREATE INDEX IF NOT EXISTS idx_endpoints_project_endpoint ON endpoints(project_id, endpoint);
diff --git a/docs/pages/client/chi-middleware/configuration.mdx b/docs/pages/client/chi-middleware/configuration.mdx
index 7db2c896..0b46e0b0 100644
--- a/docs/pages/client/chi-middleware/configuration.mdx
+++ b/docs/pages/client/chi-middleware/configuration.mdx
@@ -6,6 +6,7 @@
|--------|-------------|---------|
| `WithRepanic(bool)` | Re-panic after capturing, letting upstream recovery handle it | `true` |
| `WithIgnoredPaths(...string)` | Skip recording for specific URL paths | none |
+| `WithStreamingPaths(...string)` | Mark paths as long-lived streaming responses (SSE / WS / long-poll) | none |
| `WithFilter(func(*http.Request) bool)` | Custom filter function — return `false` to skip recording | none |
| `WithOnErrorRecording(RecordingFlag)` | What additional data to capture on errors | `0` (none) |
@@ -69,6 +70,37 @@ tracewaychi.New(
When the filter returns `false`, the request is passed directly to your handler without any Traceway wrapping.
+## Streaming Responses (SSE / WebSocket / long-poll)
+
+Long-lived streaming routes have a request lifetime that equals the connection duration, not request processing latency. Recording them as normal endpoints would dominate P50/P95/P99 rankings, tank Apdex, and trigger slow-endpoint alerts.
+
+The middleware **auto-detects** streaming responses from the response headers:
+
+| Signal | Detection |
+|--------|-----------|
+| Server-Sent Events | `Content-Type: text/event-stream` |
+| WebSocket upgrade | HTTP status `101 Switching Protocols`, or `Upgrade: websocket` |
+
+Streaming requests are still recorded — status code, error rate, and throughput remain visible — but their duration is **excluded** from P50/P95/P99, Apdex, and impact scoring.
+
+Declare paths the SDK can't auto-detect (long-polling, chunked JSON streams):
+
+```go
+tracewaychi.New(
+ connectionString,
+ tracewaychi.WithStreamingPaths("/api/long-poll", "/api/stream/json"),
+)
+```
+
+Or mark dynamically from any handler:
+
+```go
+func eventsHandler(w http.ResponseWriter, r *http.Request) {
+ traceway.MarkStream(r.Context())
+ // ... write stream ...
+}
+```
+
## Complete Example
```go
diff --git a/docs/pages/client/chi-middleware/index.mdx b/docs/pages/client/chi-middleware/index.mdx
index cbaa9567..05f6174a 100644
--- a/docs/pages/client/chi-middleware/index.mdx
+++ b/docs/pages/client/chi-middleware/index.mdx
@@ -1,5 +1,11 @@
# Chi Middleware
+import { Callout } from "nextra/components";
+
+<Callout type="warning">
+ The Traceway Go SDK is no longer the recommended way to integrate with Traceway. For new projects, instrument with [OpenTelemetry](/client/otel) — it works across languages and Traceway natively ingests OTLP. The Go SDK is still supported, but new features land in the OTel path first.
+</Callout>
+
The `tracewaychi` package provides middleware for the [Chi](https://github.com/go-chi/chi) router. It automatically creates a trace for each request, captures panics, and detects client IP addresses.
Chi is fully compatible with `net/http` middleware, so `tracewaychi` delegates to the `tracewayhttp` package internally while providing a Chi-specific API surface.
diff --git a/docs/pages/client/fasthttp-middleware/configuration.mdx b/docs/pages/client/fasthttp-middleware/configuration.mdx
index 12672ff9..b816ec87 100644
--- a/docs/pages/client/fasthttp-middleware/configuration.mdx
+++ b/docs/pages/client/fasthttp-middleware/configuration.mdx
@@ -6,6 +6,7 @@
|--------|-------------|---------|
| `WithRepanic(bool)` | Re-panic after capturing, letting upstream recovery handle it | `true` |
| `WithIgnoredPaths(...string)` | Skip recording for specific URL paths | none |
+| `WithStreamingPaths(...string)` | Mark paths as long-lived streaming responses (SSE / WS / long-poll) | none |
| `WithFilter(func(*fasthttp.RequestCtx) bool)` | Custom filter function — return `false` to skip recording | none |
| `WithOnErrorRecording(RecordingFlag)` | What additional data to capture on errors | `0` (none) |
@@ -69,6 +70,28 @@ tracewayfasthttp.New(
When the filter returns `false`, the request is passed directly to your handler without any Traceway wrapping.
+## Streaming Responses (SSE / WebSocket / long-poll)
+
+Long-lived streaming routes have a request lifetime that equals the connection duration, not request processing latency. The middleware **auto-detects** streaming responses from the response headers (SSE `Content-Type: text/event-stream`, WebSocket upgrade status `101` or `Upgrade: websocket`) and excludes them from P50/P95/P99, Apdex, and impact scoring while keeping their status code, error rate, and throughput visible on the dashboard.
+
+For paths the SDK can't auto-detect:
+
+```go
+tracewayfasthttp.New(
+ connectionString,
+ tracewayfasthttp.WithStreamingPaths("/api/long-poll", "/api/stream/json"),
+)
+```
+
+Or mark dynamically from any handler:
+
+```go
+func eventsHandler(ctx *fasthttp.RequestCtx) {
+ tracewayfasthttp.MarkStream(ctx)
+ // ... write stream ...
+}
+```
+
## Complete Example
```go
diff --git a/docs/pages/client/fasthttp-middleware/index.mdx b/docs/pages/client/fasthttp-middleware/index.mdx
index a9c64584..19c30bb9 100644
--- a/docs/pages/client/fasthttp-middleware/index.mdx
+++ b/docs/pages/client/fasthttp-middleware/index.mdx
@@ -1,5 +1,11 @@
# FastHTTP Middleware
+import { Callout } from "nextra/components";
+
+<Callout type="warning">
+ The Traceway Go SDK is no longer the recommended way to integrate with Traceway. For new projects, instrument with [OpenTelemetry](/client/otel) — it works across languages and Traceway natively ingests OTLP. The Go SDK is still supported, but new features land in the OTel path first.
+</Callout>
+
The `tracewayfasthttp` package provides middleware for the [FastHTTP](https://github.com/valyala/fasthttp) server. It automatically creates a trace for each request, captures panics, and detects client IP addresses.
## Installation
diff --git a/docs/pages/client/fiber-middleware/configuration.mdx b/docs/pages/client/fiber-middleware/configuration.mdx
index fa5a3f8a..63e91628 100644
--- a/docs/pages/client/fiber-middleware/configuration.mdx
+++ b/docs/pages/client/fiber-middleware/configuration.mdx
@@ -7,6 +7,7 @@
| `WithRepanic(bool)` | Re-panic after capturing, letting upstream recovery handle it | `true` |
| `WithRecordUnmatched(bool)` | Record requests for unregistered routes (404s) | `false` |
| `WithIgnoredPaths(...string)` | Skip recording for specific route paths | none |
+| `WithStreamingPaths(...string)` | Mark routes as long-lived streaming responses (SSE / WS / long-poll) | none |
| `WithFilter(func(*fiber.Ctx) bool)` | Custom filter function — return `false` to skip recording | none |
| `WithOnErrorRecording(RecordingFlag)` | What additional data to capture on errors | `0` (none) |
@@ -78,6 +79,29 @@ tracewayfiber.New(
When the filter returns `false`, the request is passed directly to your handler without any Traceway wrapping.
+## Streaming Responses (SSE / WebSocket / long-poll)
+
+Long-lived streaming routes have a request lifetime that equals the connection duration, not request processing latency. The middleware **auto-detects** streaming responses from the response headers (SSE `Content-Type: text/event-stream`, WebSocket upgrade status `101` or `Upgrade: websocket`) and excludes them from P50/P95/P99, Apdex, and impact scoring while keeping their status code, error rate, and throughput visible on the dashboard.
+
+For routes the SDK can't auto-detect:
+
+```go
+tracewayfiber.New(
+ connectionString,
+ tracewayfiber.WithStreamingPaths("/api/long-poll", "/api/stream/json"),
+)
+```
+
+Or mark dynamically from any handler:
+
+```go
+func eventsHandler(c *fiber.Ctx) error {
+ tracewayfiber.MarkStream(c)
+ // ... write stream ...
+ return nil
+}
+```
+
## Complete Example
```go
diff --git a/docs/pages/client/fiber-middleware/index.mdx b/docs/pages/client/fiber-middleware/index.mdx
index 153cc5db..6f6d3474 100644
--- a/docs/pages/client/fiber-middleware/index.mdx
+++ b/docs/pages/client/fiber-middleware/index.mdx
@@ -1,5 +1,11 @@
# Fiber Middleware
+import { Callout } from "nextra/components";
+
+<Callout type="warning">
+ The Traceway Go SDK is no longer the recommended way to integrate with Traceway. For new projects, instrument with [OpenTelemetry](/client/otel) — it works across languages and Traceway natively ingests OTLP. The Go SDK is still supported, but new features land in the OTel path first.
+</Callout>
+
The `tracewayfiber` package provides middleware for the [Fiber](https://gofiber.io/) web framework. It automatically creates a trace for each request, captures panics and handler errors, and detects client IP addresses.
## Installation
diff --git a/docs/pages/client/gin-middleware/configuration.mdx b/docs/pages/client/gin-middleware/configuration.mdx
index aeee885d..7ab81a2e 100644
--- a/docs/pages/client/gin-middleware/configuration.mdx
+++ b/docs/pages/client/gin-middleware/configuration.mdx
@@ -8,6 +8,7 @@
| `WithRecordUnmatched(bool)` | Record requests for unregistered routes (404s) | `false` |
| `WithRecordStatic(bool)` | Record requests for static file routes | `false` |
| `WithIgnoredPaths(...string)` | Skip recording for specific route paths | none |
+| `WithStreamingPaths(...string)` | Mark routes as long-lived streaming responses (SSE / WS / long-poll) | none |
| `WithOnErrorRecording(RecordingFlag)` | What additional data to capture on errors | `0` (none) |
## Passthrough Core Options
@@ -62,6 +63,34 @@ tracewaygin.WithIgnoredPaths("/health", "/ready", "/metrics")
Ignored paths are still served — the request passes through to your handler, but no trace is recorded.
+## Streaming Responses (SSE / WebSocket / long-poll)
+
+Long-lived streaming routes — Server-Sent Events, WebSocket connections, long-polling — have a request lifetime that equals the connection duration, not request processing latency. If they were recorded as normal endpoints they would dominate P50/P95/P99 rankings, tank Apdex, and trigger slow-endpoint alerts even when behaving correctly.
+
+The middleware **auto-detects** streaming responses by inspecting the response headers after the handler returns:
+
+| Signal | Detection |
+|--------|-----------|
+| Server-Sent Events | `Content-Type: text/event-stream` |
+| WebSocket upgrade | HTTP status `101 Switching Protocols`, or `Upgrade: websocket` |
+
+When a streaming response is detected the trace is still recorded — its status code, error rate, and throughput remain visible on the dashboard — but its duration is **excluded** from P50/P95/P99, Apdex, and impact scoring.
+
+For routes the SDK can't auto-detect (long-polling, chunked JSON streams, custom protocols), declare them up-front:
+
+```go
+tracewaygin.WithStreamingPaths("/api/long-poll", "/api/stream/json")
+```
+
+Or mark dynamically from any handler reachable on the request — useful when the same route is sometimes streaming, sometimes not:
+
+```go
+func eventsHandler(c *gin.Context) {
+ traceway.MarkStream(c.Request.Context())
+ // ... write stream ...
+}
+```
+
## Complete Example
```go
diff --git a/docs/pages/client/gin-middleware/index.mdx b/docs/pages/client/gin-middleware/index.mdx
index 5a43625d..c1af773e 100644
--- a/docs/pages/client/gin-middleware/index.mdx
+++ b/docs/pages/client/gin-middleware/index.mdx
@@ -1,5 +1,11 @@
# Gin Middleware
+import { Callout } from "nextra/components";
+
+<Callout type="warning">
+ The Traceway Go SDK is no longer the recommended way to integrate with Traceway. For new projects, instrument with [OpenTelemetry](/client/otel) — it works across languages and Traceway natively ingests OTLP. The Go SDK is still supported, but new features land in the OTel path first.
+</Callout>
+
The `tracewaygin` package provides middleware for the [Gin](https://gin-gonic.com/) web framework. It automatically creates a trace for each request, captures panics, and detects errors from Gin's error chain.
## Installation
diff --git a/docs/pages/client/http-middleware/configuration.mdx b/docs/pages/client/http-middleware/configuration.mdx
index 978c0e9c..be02207b 100644
--- a/docs/pages/client/http-middleware/configuration.mdx
+++ b/docs/pages/client/http-middleware/configuration.mdx
@@ -6,6 +6,7 @@
|--------|-------------|---------|
| `WithRepanic(bool)` | Re-panic after capturing, letting upstream recovery handle it | `true` |
| `WithIgnoredPaths(...string)` | Skip recording for specific URL paths | none |
+| `WithStreamingPaths(...string)` | Mark paths as long-lived streaming responses (SSE / WS / long-poll) | none |
| `WithFilter(func(*http.Request) bool)` | Custom filter function — return `false` to skip recording | none |
| `WithOnErrorRecording(RecordingFlag)` | What additional data to capture on errors | `0` (none) |
@@ -69,6 +70,37 @@ tracewayhttp.New(
When the filter returns `false`, the request is passed directly to your handler without any Traceway wrapping.
+## Streaming Responses (SSE / WebSocket / long-poll)
+
+Long-lived streaming routes have a request lifetime that equals the connection duration, not request processing latency. Recording them as normal endpoints would dominate P50/P95/P99 rankings, tank Apdex, and trigger slow-endpoint alerts.
+
+The middleware **auto-detects** streaming responses by inspecting the response headers after the handler returns:
+
+| Signal | Detection |
+|--------|-----------|
+| Server-Sent Events | `Content-Type: text/event-stream` |
+| WebSocket upgrade | HTTP status `101 Switching Protocols`, or `Upgrade: websocket` |
+
+Streaming requests are still recorded — status code, error rate, and throughput remain visible on the dashboard — but their duration is **excluded** from P50/P95/P99, Apdex, and impact scoring.
+
+For paths the SDK can't auto-detect (long-polling, chunked JSON streams, custom protocols), declare them up-front:
+
+```go
+tracewayhttp.New(
+ connectionString,
+ tracewayhttp.WithStreamingPaths("/api/long-poll", "/api/stream/json"),
+)
+```
+
+Or mark dynamically from any handler:
+
+```go
+func eventsHandler(w http.ResponseWriter, r *http.Request) {
+ traceway.MarkStream(r.Context())
+ // ... write stream ...
+}
+```
+
## Differences from Gin Middleware
The HTTP middleware does **not** have `WithRecordUnmatched` or `WithRecordStatic` options — these are Gin-specific because `net/http` has no built-in route registration to distinguish matched vs unmatched routes.
diff --git a/docs/pages/client/http-middleware/index.mdx b/docs/pages/client/http-middleware/index.mdx
index 36e9cea8..ffc76204 100644
--- a/docs/pages/client/http-middleware/index.mdx
+++ b/docs/pages/client/http-middleware/index.mdx
@@ -1,5 +1,11 @@
# HTTP Middleware
+import { Callout } from "nextra/components";
+
+<Callout type="warning">
+ The Traceway Go SDK is no longer the recommended way to integrate with Traceway. For new projects, instrument with [OpenTelemetry](/client/otel) — it works across languages and Traceway natively ingests OTLP. The Go SDK is still supported, but new features land in the OTel path first.
+</Callout>
+
The `tracewayhttp` package provides middleware for standard `net/http` servers. It automatically creates a trace for each request, captures panics, and detects client IP addresses.
## Installation
diff --git a/docs/pages/client/otel/traces.mdx b/docs/pages/client/otel/traces.mdx
index cee2fed2..43f604e8 100644
--- a/docs/pages/client/otel/traces.mdx
+++ b/docs/pages/client/otel/traces.mdx
@@ -38,6 +38,18 @@ For root SERVER spans with HTTP attributes, Traceway extracts the following:
The endpoint name is constructed as `"METHOD /route"` (e.g., `"GET /api/users"`).
+### Streaming Responses (SSE / WebSocket)
+
+Long-lived streaming routes are flagged as `is_stream` on ingest so that the dashboard excludes them from P50/P95/P99, Apdex, and impact scoring. They still appear in the endpoints list with their count, status code, error rate, and throughput. Detection signals (any of):
+
+| Signal | OTel attribute |
+|--------|----------------|
+| Server-Sent Events | `http.response.header.content-type` contains `text/event-stream` |
+| WebSocket upgrade | `http.response.status_code = 101` |
+| Vendor opt-in | `traceway.is_stream = true` (bool) — for protocols the headers don't expose |
+
+There is no OpenTelemetry-standard streaming attribute; Traceway sniffs the captured Content-Type response header. Make sure your OTel instrumentation actually captures `http.response.header.content-type` (some SDKs require explicit opt-in for header capture). Otherwise set `traceway.is_stream = true` directly on the span when starting a stream.
+
## Exception Events
Spans with events named `"exception"` are extracted as Issues in Traceway. The following event attributes are used:
diff --git a/examples/devtesting-embedded/main.go b/examples/devtesting-embedded/main.go
index a5e5aff9..6496aa96 100644
--- a/examples/devtesting-embedded/main.go
+++ b/examples/devtesting-embedded/main.go
@@ -295,6 +295,28 @@ func main() {
})
})
+ router.GET("/api/test-sse", func(c *gin.Context) {
+ span := trace.SpanFromContext(c.Request.Context())
+ span.SetAttributes(attribute.Bool("traceway.is_stream", true))
+ writeSSEStream(c, 30*time.Second, time.Second)
+ })
+
+ // Short SSE for quicker iteration.
+ router.GET("/api/test-sse-short", func(c *gin.Context) {
+ span := trace.SpanFromContext(c.Request.Context())
+ span.SetAttributes(attribute.Bool("traceway.is_stream", true))
+ writeSSEStream(c, 5*time.Second, 500*time.Millisecond)
+ })
+
+ // Long-poll style — no SSE Content-Type, just a long-held connection that
+ // returns JSON at the end. Flagged via the same span attribute.
+ router.GET("/api/test-long-poll", func(c *gin.Context) {
+ span := trace.SpanFromContext(c.Request.Context())
+ span.SetAttributes(attribute.Bool("traceway.is_stream", true))
+ time.Sleep(10 * time.Second)
+ c.JSON(http.StatusOK, gin.H{"status": "ok", "via": "long-poll"})
+ })
+
fmt.Println()
fmt.Println("=================================================")
fmt.Printf(" Node build: http://localhost:%d\n", appPort)
@@ -308,8 +330,40 @@ func main() {
fmt.Printf(" curl http://localhost:%d/api/test-log-levels\n", appPort)
fmt.Printf(" curl http://localhost:%d/api/test-spans-with-logs\n", appPort)
fmt.Printf(" curl http://localhost:%d/api/test-distributed-logs\n", appPort)
+ fmt.Println()
+ fmt.Println(" Streaming endpoints (is_stream — expect a 'Stream' badge):")
+ fmt.Printf(" curl -N http://localhost:%d/api/test-sse\n", appPort)
+ fmt.Printf(" curl -N http://localhost:%d/api/test-sse-short\n", appPort)
+ fmt.Printf(" curl http://localhost:%d/api/test-long-poll\n", appPort)
fmt.Println("=================================================")
fmt.Println()
router.Run(fmt.Sprintf(":%d", appPort))
}
+func writeSSEStream(c *gin.Context, duration, interval time.Duration) {
+ c.Writer.Header().Set("Content-Type", "text/event-stream")
+ c.Writer.Header().Set("Cache-Control", "no-cache")
+ c.Writer.Header().Set("Connection", "keep-alive")
+ c.Writer.Header().Set("X-Accel-Buffering", "no")
+ c.Writer.WriteHeader(http.StatusOK)
+ c.Writer.Flush()
+
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ timeout := time.After(duration)
+
+ clientGone := c.Request.Context().Done()
+ tick := 0
+ for {
+ select {
+ case <-clientGone:
+ return
+ case <-timeout:
+ return
+ case t := <-ticker.C:
+ tick++
+ fmt.Fprintf(c.Writer, "event: tick\ndata: {\"n\":%d,\"time\":\"%s\"}\n\n", tick, t.Format(time.RFC3339Nano))
+ c.Writer.Flush()
+ }
+ }
+}
diff --git a/frontend/src/lib/components/issues/page-header.svelte b/frontend/src/lib/components/issues/page-header.svelte
index 828a144f..69a1f439 100644
--- a/frontend/src/lib/components/issues/page-header.svelte
+++ b/frontend/src/lib/components/issues/page-header.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import { goto } from '$app/navigation';
+ import type { Snippet } from 'svelte';
import { Button } from "$lib/components/ui/button";
import { ArrowLeft } from "lucide-svelte";
@@ -7,9 +7,10 @@
title: string;
subtitle?: string;
onBack?: (e: MouseEvent) => void;
+ trailing?: Snippet;
}
- let { title, subtitle, onBack }: Props = $props();
+ let { title, subtitle, onBack, trailing }: Props = $props();
</script>
<div class="flex items-start gap-4">
@@ -19,9 +20,12 @@
</Button>
{/if}
<div>
- <h2 class="font-mono text-2xl font-bold tracking-tight break-all">
- {title}
- </h2>
+ <div class="flex flex-wrap items-center gap-2">
+ <h2 class="font-mono text-2xl font-bold tracking-tight break-all">
+ {title}
+ </h2>
+ {#if trailing}{@render trailing()}{/if}
+ </div>
{#if subtitle}
<p class="text-muted-foreground text-sm">{subtitle}</p>
{/if}
diff --git a/frontend/src/routes/endpoints/+page.svelte b/frontend/src/routes/endpoints/+page.svelte
index e4ab4d5d..5e0e51e6 100644
--- a/frontend/src/routes/endpoints/+page.svelte
+++ b/frontend/src/routes/endpoints/+page.svelte
@@ -11,6 +11,7 @@
import { ChevronDown, Check } from 'lucide-svelte';
import { TracewayTableHeader } from "$lib/components/ui/traceway-table-header";
import { ImpactBadge } from "$lib/components/ui/impact-badge";
+ import { Badge } from "$lib/components/ui/badge";
import { TableEmptyState } from "$lib/components/ui/table-empty-state";
import { PaginationFooter } from "$lib/components/ui/pagination-footer";
import { TimeRangePicker } from "$lib/components/ui/time-range-picker";
@@ -52,6 +53,7 @@
lastSeen: string;
impact: number;
impactReason: string;
+ isStream?: boolean;
};
type SortField = 'count' | 'p50_duration' | 'p95_duration' | 'p99_duration' | 'last_seen' | 'impact';
@@ -543,19 +545,24 @@
onclick={createRowClickHandler(resolve(`/endpoints/${encodeURIComponent(endpoint.endpoint)}`), 'preset', 'from', 'to')}
>
<Table.Cell class="font-mono text-sm max-w-[50%] break-all whitespace-normal">
- {endpoint.endpoint}
+ <span class="inline-flex items-center gap-2">
+ {endpoint.endpoint}
+ {#if endpoint.isStream}
+ <Badge variant="outline" class="font-sans text-xs" title="Streaming response (SSE / WebSocket / long-poll). Excluded from latency, Apdex, and impact scoring.">Stream</Badge>
+ {/if}
+ </span>
</Table.Cell>
<Table.Cell class="tabular-nums">
{formatCount(endpoint.count)}
</Table.Cell>
- <Table.Cell class="font-mono text-sm tabular-nums">
- {formatDuration(endpoint.p50Duration)}
+ <Table.Cell class="font-mono text-sm tabular-nums text-muted-foreground">
+ {endpoint.isStream ? '—' : formatDuration(endpoint.p50Duration)}
</Table.Cell>
- <Table.Cell class="font-mono text-sm tabular-nums">
- {formatDuration(endpoint.p95Duration)}
+ <Table.Cell class="font-mono text-sm tabular-nums text-muted-foreground">
+ {endpoint.isStream ? '—' : formatDuration(endpoint.p95Duration)}
</Table.Cell>
- <Table.Cell class="font-mono text-sm tabular-nums">
- {formatDuration(endpoint.p99Duration)}
+ <Table.Cell class="font-mono text-sm tabular-nums text-muted-foreground">
+ {endpoint.isStream ? '—' : formatDuration(endpoint.p99Duration)}
</Table.Cell>
<Table.Cell class="text-right">
<ImpactBadge score={endpoint.impact} reason={endpoint.impactReason} />
diff --git a/frontend/src/routes/endpoints/[endpoint]/+page.svelte b/frontend/src/routes/endpoints/[endpoint]/+page.svelte
index 75a9a692..030404b6 100644
--- a/frontend/src/routes/endpoints/[endpoint]/+page.svelte
+++ b/frontend/src/routes/endpoints/[endpoint]/+page.svelte
@@ -28,6 +28,8 @@
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 * as Tooltip from '$lib/components/ui/tooltip';
+ import { Badge } from '$lib/components/ui/badge';
import { toast } from 'svelte-sonner';
import { resolve } from '$app/paths';
import {
@@ -70,6 +72,7 @@
apdex: number;
errorRate: number;
throughput: number;
+ isStream?: boolean;
};
type SortField = 'recorded_at' | 'duration' | 'status_code' | 'body_size';
@@ -361,13 +364,28 @@
title={decodeURIComponent(data.endpoint)}
subtitle="Trace instances for this endpoint"
onBack={goBackToEndpoints}
- />
+ >
+ {#snippet trailing()}
+ {#if stats?.isStream}
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ <Badge variant="outline" class="font-sans">Stream</Badge>
+ </Tooltip.Trigger>
+ <Tooltip.Content side="bottom" class="max-w-xs">
+ Streaming endpoint — latency metrics aren't tracked.
+ </Tooltip.Content>
+ </Tooltip.Root>
+ {/if}
+ {/snippet}
+ </PageHeader>
<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>
+ {#if !stats?.isStream}
+ <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>
+ {/if}
<TimeRangePicker
bind:fromDate
bind:toDate
@@ -379,7 +397,7 @@
</div>
</div>
- {#if offsetMs > 0}
+ {#if offsetMs > 0 && !stats?.isStream}
<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>
@@ -393,38 +411,55 @@
<!-- Endpoint Stats -->
{#if stats}
- <div class="grid grid-cols-2 gap-4 md:grid-cols-4 lg:grid-cols-7">
- <div class="space-y-1">
- <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.avgDuration)}</p>
- <p class="text-xs text-muted-foreground">Average response time</p>
- </div>
- <div class="space-y-1">
- <p class="text-2xl font-semibold tracking-tight">
- {formatDurationMs(stats.medianDuration)}
- </p>
- <p class="text-xs text-muted-foreground">Median response time</p>
- </div>
- <div class="space-y-1">
- <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.p95Duration)}</p>
- <p class="text-xs text-muted-foreground">95th percentile response time</p>
+ {#if stats.isStream}
+ <div class="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-3">
+ <div class="space-y-1">
+ <p class="text-2xl font-semibold tracking-tight">{stats.count.toLocaleString()}</p>
+ <p class="text-xs text-muted-foreground">Connections</p>
+ </div>
+ <div class="space-y-1">
+ <p class="text-2xl font-semibold tracking-tight">{stats.errorRate.toFixed(2)} %</p>
+ <p class="text-xs text-muted-foreground">Average error rate</p>
+ </div>
+ <div class="space-y-1">
+ <p class="text-2xl font-semibold tracking-tight">{stats.throughput.toFixed(0)} rpm</p>
+ <p class="text-xs text-muted-foreground">Average throughput</p>
+ </div>
</div>
- <div class="space-y-1">
- <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.p99Duration)}</p>
- <p class="text-xs text-muted-foreground">99th percentile response time</p>
+ {:else}
+ <div class="grid grid-cols-2 gap-4 md:grid-cols-4 lg:grid-cols-7">
+ <div class="space-y-1">
+ <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.avgDuration)}</p>
+ <p class="text-xs text-muted-foreground">Average response time</p>
+ </div>
+ <div class="space-y-1">
+ <p class="text-2xl font-semibold tracking-tight">
+ {formatDurationMs(stats.medianDuration)}
+ </p>
+ <p class="text-xs text-muted-foreground">Median response time</p>
+ </div>
+ <div class="space-y-1">
+ <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.p95Duration)}</p>
+ <p class="text-xs text-muted-foreground">95th percentile response time</p>
+ </div>
+ <div class="space-y-1">
+ <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.p99Duration)}</p>
+ <p class="text-xs text-muted-foreground">99th percentile response time</p>
+ </div>
+ <div class="space-y-1">
+ <p class="text-2xl font-semibold tracking-tight">{stats.apdex.toFixed(2)}</p>
+ <p class="text-xs text-muted-foreground">Apdex score</p>
+ </div>
+ <div class="space-y-1">
+ <p class="text-2xl font-semibold tracking-tight">{stats.errorRate.toFixed(2)} %</p>
+ <p class="text-xs text-muted-foreground">Average error rate</p>
+ </div>
+ <div class="space-y-1">
+ <p class="text-2xl font-semibold tracking-tight">{stats.throughput.toFixed(0)} rpm</p>
+ <p class="text-xs text-muted-foreground">Average throughput</p>
+ </div>
</div>
- <div class="space-y-1">
- <p class="text-2xl font-semibold tracking-tight">{stats.apdex.toFixed(2)}</p>
- <p class="text-xs text-muted-foreground">Apdex score</p>
- </div>
- <div class="space-y-1">
- <p class="text-2xl font-semibold tracking-tight">{stats.errorRate.toFixed(2)} %</p>
- <p class="text-xs text-muted-foreground">Average error rate</p>
- </div>
- <div class="space-y-1">
- <p class="text-2xl font-semibold tracking-tight">{stats.throughput.toFixed(0)} rpm</p>
- <p class="text-xs text-muted-foreground">Average throughput</p>
- </div>
- </div>
+ {/if}
{:else if loading}
<div class="flex items-center justify-center py-8">
<LoadingCircle size="lg" />
diff --git a/testing/devtesting/devtesting.go b/testing/devtesting/devtesting.go
index 711c43d4..ba8c47c9 100644
--- a/testing/devtesting/devtesting.go
+++ b/testing/devtesting/devtesting.go
@@ -88,6 +88,10 @@ func testGin() {
tracewaygin.WithDebug(true),
// tracewaygin.WithRepanic(true),
tracewaygin.WithOnErrorRecording(tracewaygin.RecordingUrl|tracewaygin.RecordingQuery|tracewaygin.RecordingHeader|tracewaygin.RecordingBody),
+ // /test-stream-config does not set a streaming Content-Type, so it can't be
+ // auto-sniffed. Declaring it here marks it as a stream up-front. Useful for
+ // long-poll / chunked-JSON routes that look like normal requests on the wire.
+ tracewaygin.WithStreamingPaths("/test-stream-config"),
))
router.POST("/test-recording/:param", func(ctx *gin.Context) {
@@ -183,6 +187,32 @@ func testGin() {
})
})
+ // SSE auto-detection — middleware sniffs Content-Type: text/event-stream.
+ router.GET("/test-sse", func(ctx *gin.Context) {
+ writeSSEStream(ctx, 30*time.Second, time.Second)
+ })
+
+ // Short SSE — same auto-detection, faster turnaround for iterating.
+ router.GET("/test-sse-short", func(ctx *gin.Context) {
+ writeSSEStream(ctx, 5*time.Second, 500*time.Millisecond)
+ })
+
+ // Explicit MarkStream — no streaming Content-Type, but the handler flags
+ // the request mid-flight. Mirrors long-poll / chunked-JSON cases.
+ router.GET("/test-stream-marked", func(ctx *gin.Context) {
+ traceway.MarkStream(ctx.Request.Context())
+ // Pretend to long-poll for ~10s then return JSON.
+ time.Sleep(10 * time.Second)
+ ctx.JSON(http.StatusOK, gin.H{"status": "ok", "via": "MarkStream"})
+ })
+
+ // Per-route config — registered via WithStreamingPaths above. No header,
+ // no API call, but flagged by path because the SDK can't sniff this case.
+ router.GET("/test-stream-config", func(ctx *gin.Context) {
+ time.Sleep(8 * time.Second)
+ ctx.JSON(http.StatusOK, gin.H{"status": "ok", "via": "WithStreamingPaths"})
+ })
+
router.GET("/test-spans", func(ctx *gin.Context) {
dbAndCacheSpan := traceway.StartSpan(ctx, "db.and.cache")
@@ -281,7 +311,7 @@ func testGin() {
router.PUT("/users/:id", updateUser)
router.DELETE("/users/:id", deleteUser)
- router.Run()
+ router.Run(":8081")
}
func listUsers(c *gin.Context) {
@@ -385,4 +415,32 @@ func deleteUser(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "user deleted"})
}
+func writeSSEStream(ctx *gin.Context, duration, interval time.Duration) {
+ ctx.Writer.Header().Set("Content-Type", "text/event-stream")
+ ctx.Writer.Header().Set("Cache-Control", "no-cache")
+ ctx.Writer.Header().Set("Connection", "keep-alive")
+ ctx.Writer.Header().Set("X-Accel-Buffering", "no")
+ ctx.Writer.WriteHeader(http.StatusOK)
+ ctx.Writer.Flush()
+
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ timeout := time.After(duration)
+
+ clientGone := ctx.Request.Context().Done()
+ tick := 0
+ for {
+ select {
+ case <-clientGone:
+ return
+ case <-timeout:
+ return
+ case t := <-ticker.C:
+ tick++
+ fmt.Fprintf(ctx.Writer, "event: tick\ndata: {\"n\":%d,\"time\":\"%s\"}\n\n", tick, t.Format(time.RFC3339Nano))
+ ctx.Writer.Flush()
+ }
+ }
+}
+
var veryLongJsonForTestin = `{"str": "traceway", "obj": {"id": 1}, "obj2": {"id": 1}, "obj3": {"id": 1}, "obj4": {"id": 1}, "obj5loremipsumdoloret": {"id": "I'm baby tumeric VHS Brooklyn, echo park literally you probably haven't heard of them crucifix taiyaki chambray roof party man bun knausgaard waistcoat squid health goth. Gastropub godard bodega boys snackwave asymmetrical la croix. Whatever try-hard pour-over humblebrag austin microdosing organic bruh. Keffiyeh mukbang yuccie, 90's humblebrag roof party godard kale chips lo-fi sriracha aesthetic.", "id2": "ImbabytumericVHSBrooklynechoparkliterallyyouprobablyhaventheardofthemcrucifixtaiyakichambrayroofpartymanbunknausgaardwaistcoatsquidhealthgothGastropubgodardbodegaboyssnackwaveasymmetricallacroixWhatevertryhardpouroverhumblebragaustinmicrodosingorganicbruhKeffiyehmukbangyuccieshumblebragroofpartygodardkalechipslofisrirachaaesthetic"}, "arr": [1, 2, "", {"key": 1, "key2": "example"}]}`
diff --git a/testing/devtesting/go.mod b/testing/devtesting/go.mod
index 0a033e40..80704e2b 100644
--- a/testing/devtesting/go.mod
+++ b/testing/devtesting/go.mod
@@ -5,7 +5,7 @@ go 1.25.1
require (
github.com/gin-gonic/gin v1.11.0
github.com/mattn/go-sqlite3 v1.14.33
- go.tracewayapp.com v0.4.3
+ go.tracewayapp.com v1.0.2
go.tracewayapp.com/tracewaydb v0.0.0-00010101000000-000000000000
go.tracewayapp.com/tracewaygin v0.0.0-00010101000000-000000000000
)