-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathobservability.go
More file actions
280 lines (239 loc) · 8.61 KB
/
observability.go
File metadata and controls
280 lines (239 loc) · 8.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// Copyright 2025 The Rivaas Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app
import (
"context"
"io"
"log/slog"
"net/http"
"time"
"go.opentelemetry.io/otel/trace"
"rivaas.dev/metrics"
"rivaas.dev/router"
"rivaas.dev/tracing"
stderrors "errors"
)
// observabilityWrappedWriter detects if an http.ResponseWriter has already
// been wrapped by observability middleware, preventing double-wrapping.
// Uses Go structural typing — any writer implementing this method from any
// package (tracing, metrics, app, or user code) will be detected.
type observabilityWrappedWriter interface {
IsObservabilityWrapped() bool
}
// observabilityRecorder implements [router.ObservabilityRecorder] by unifying
// metrics, tracing, and logging into a single lifecycle.
// It coordinates observability data collection across all three pillars.
type observabilityRecorder struct {
metrics *metrics.Recorder
tracing *tracing.Tracer
logger *slog.Logger
pathFilter *pathFilter
// Access log configuration
logAccessRequests bool
logErrorsOnly bool
slowThreshold time.Duration
}
// recorderConfig configures the unified observability recorder.
type recorderConfig struct {
metrics *metrics.Recorder
tracing *tracing.Tracer
logger *slog.Logger
pathFilter *pathFilter
logAccessRequests bool
logErrorsOnly bool
slowThreshold time.Duration
}
// newObservabilityRecorder creates an [observabilityRecorder] from configuration.
func newObservabilityRecorder(cfg *recorderConfig) router.ObservabilityRecorder {
pf := cfg.pathFilter
if pf == nil {
pf = newPathFilterWithDefaults()
}
return &observabilityRecorder{
metrics: cfg.metrics,
tracing: cfg.tracing,
logger: cfg.logger,
pathFilter: pf,
logAccessRequests: cfg.logAccessRequests,
logErrorsOnly: cfg.logErrorsOnly,
slowThreshold: cfg.slowThreshold,
}
}
// observabilityState is the opaque token holding per-request observability state
// passed between lifecycle methods.
type observabilityState struct {
metricsData *metrics.RequestMetrics // Metrics state from metrics.BeginRequest
span trace.Span // Active span from tracing
startTime time.Time // Request start time for duration calculation
req *http.Request // Original request for access logging
}
func (o *observabilityRecorder) OnRequestStart(ctx context.Context, req *http.Request) (context.Context, any) {
// Single source of truth for exclusions
if o.pathFilter != nil && o.pathFilter.shouldExclude(req.URL.Path) {
return ctx, nil // Excluded: skip all observability
}
state := &observabilityState{
startTime: time.Now(),
req: req, // Store for later use
}
// Start tracing (if enabled)
// Use StartRequestSpan for W3C propagation, sampling, and standard HTTP attributes.
// Note: We start with raw path; will rename span to route pattern in OnRequestEnd
if o.tracing != nil && o.tracing.IsEnabled() {
ctx, state.span = o.tracing.StartRequestSpan(ctx, req, req.URL.Path, false)
}
// Start metrics (if enabled)
// Note: We'll update with route pattern in OnRequestEnd for cardinality control
if o.metrics != nil && o.metrics.IsEnabled() {
state.metricsData = o.metrics.BeginRequest(ctx)
}
return ctx, state
}
func (o *observabilityRecorder) WrapResponseWriter(w http.ResponseWriter, state any) http.ResponseWriter {
if state == nil {
return w // Excluded: don't wrap
}
// Check if already wrapped by observability middleware
// This prevents double-wrapping when combining app observability with standalone middleware
if _, ok := w.(observabilityWrappedWriter); ok {
return w // Already wrapped, don't wrap again
}
return &observabilityResponseWriter{ResponseWriterWrapper: router.NewResponseWriterWrapper(w)}
}
func (o *observabilityRecorder) OnRequestEnd(ctx context.Context, state any, writer http.ResponseWriter, routePattern string) {
s, ok := state.(*observabilityState)
if !ok || s == nil {
return // Excluded or invalid state
}
duration := time.Since(s.startTime)
// Extract response metadata from wrapped writer
statusCode := http.StatusOK
var responseSize int64 = 0
if ri, riOk := writer.(router.ResponseInfo); riOk {
statusCode = ri.StatusCode()
responseSize = ri.Size()
}
// Update span name to use route pattern (better cardinality)
if s.span != nil && s.span.IsRecording() && routePattern != "" {
spanName := s.req.Method + " " + routePattern
s.span.SetName(spanName)
}
// Finish tracing (sets http.status_code and invokes span finish hook if configured)
if s.span != nil {
o.tracing.FinishRequestSpan(s.span, statusCode)
}
// Finish metrics with route pattern (prevents cardinality explosion)
if s.metricsData != nil {
// Use routePattern for metrics to avoid high cardinality
// If no route matched, use sentinel value
route := routePattern
if route == "" {
route = "_unmatched"
}
o.metrics.Finish(ctx, s.metricsData, statusCode, responseSize, route)
}
// Access logging (if enabled)
if o.logAccessRequests && o.logger != nil {
o.logAccessRequest(ctx, s.req, statusCode, responseSize, duration, routePattern)
}
}
func (o *observabilityRecorder) logAccessRequest(
ctx context.Context,
req *http.Request,
statusCode int,
responseSize int64,
duration time.Duration,
routePattern string,
) {
isError := statusCode >= 400
isSlow := o.slowThreshold > 0 && duration >= o.slowThreshold
// Skip non-errors if error-only mode (unless slow)
if o.logErrorsOnly && !isError && !isSlow {
return
}
// Build structured log fields
fields := []any{
"method", req.Method,
"path", req.URL.Path,
"status", statusCode,
"duration_ms", duration.Milliseconds(),
"bytes_sent", responseSize,
"user_agent", req.UserAgent(),
"remote_addr", req.RemoteAddr, // Added: raw remote address
"host", req.Host,
"proto", req.Proto,
}
// Add route template (key for aggregation)
if routePattern != "" {
fields = append(fields, "route", routePattern)
}
// Add request ID (for correlation)
if reqID := req.Header.Get("X-Request-ID"); reqID != "" {
fields = append(fields, "request_id", reqID)
}
// Mark slow requests explicitly
if isSlow {
fields = append(fields, "slow", true)
}
// Log at appropriate level
// Note: Slow 200s appear as warnings (intentional)
switch {
case statusCode >= 500:
o.logger.ErrorContext(ctx, "http request", fields...)
case statusCode >= 400:
o.logger.WarnContext(ctx, "http request", fields...)
case isSlow:
o.logger.WarnContext(ctx, "http request", fields...) // Slow success still notable
default:
o.logger.InfoContext(ctx, "http request", fields...)
}
}
// observabilityResponseWriter wraps [http.ResponseWriter] to capture metadata.
// It embeds [router.ResponseWriterWrapper] and adds Push, ReadFrom, and the observability marker.
type observabilityResponseWriter struct {
*router.ResponseWriterWrapper
}
// Ensure we implement required interfaces
var (
_ router.ResponseInfo = (*observabilityResponseWriter)(nil)
_ router.WrittenChecker = (*observabilityResponseWriter)(nil)
_ observabilityWrappedWriter = (*observabilityResponseWriter)(nil)
)
// IsObservabilityWrapped implements observabilityWrappedWriter marker interface.
// This signals that the writer has been wrapped by observability middleware,
// preventing double-wrapping when combining app observability with standalone middleware.
func (rw *observabilityResponseWriter) IsObservabilityWrapped() bool {
return true
}
// Push preserves http.Pusher (for HTTP/2 server push).
func (rw *observabilityResponseWriter) Push(target string, opts *http.PushOptions) error {
if pusher, ok := rw.ResponseWriter.(http.Pusher); ok {
return pusher.Push(target, opts)
}
return stderrors.New("response writer does not support push")
}
// ReadFrom preserves io.ReaderFrom (for io.Copy).
func (rw *observabilityResponseWriter) ReadFrom(r io.Reader) (int64, error) {
underlying := rw.ResponseWriter
if rf, ok := underlying.(io.ReaderFrom); ok {
n, err := rf.ReadFrom(r)
rw.AddSize(n)
rw.MarkWritten()
return n, err
}
n, err := io.Copy(underlying, r)
rw.AddSize(n)
rw.MarkWritten()
return n, err
}