Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@ updates:
# The gate sat red from 30 July onwards because grpc stayed on a vulnerable
# version and nothing said so out loud. This is the part that says so.
#
# It proposes, it does not decide: expect it to offer the grpc upgrade that
# was declined on purpose, because that one pulls x/net past go 1.26 and takes
# the module floor with it, dropping every Go 1.25 consumer. Read what an
# upgrade does to the floor before merging it.
# It proposes, it does not decide. Security fixes in x/net already require
# Go 1.26; read what each later upgrade does to the module floor before merging.
- package-ecosystem: gomod
directory: /
schedule:
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/go-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ jobs:
fail-fast: false
matrix:
go-version:
- "1.25.13"
- "1.26.1"
- "1.26.10"
- "1.27.3"

steps:
- name: Checkout
Expand Down
26 changes: 25 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ This module follows the DuckBug SDK architecture from `duckbug-sdk-spec`, while

## Compatibility

- Go `1.25.13+`. The `go` directive in `go.mod` is the source of truth; this line is a copy for readers and loses to it if the two ever disagree. The floor is a patched release of the 1.25 line: earlier 1.25 patches carry advisories in `crypto/tls`, `encoding/asn1`, `net/url` and `net/http` that this module's HTTP transport reaches.
- Go `1.26.10+`. The `go` directive in `go.mod` is the source of truth. The HTTP/2 security fixes in `golang.org/x/net` require Go 1.26; the minimum uses the current patched 1.26 release. Upgrading from SDK 0.4 also requires upgrading consumers still using Go 1.25.
- Every change is validated on that minimum and on the current Go release. The exact versions are the matrix in the CI workflow under `.github/workflows/`, and are not repeated here.
- Releases are expected to be published via git tags in the `v*` format.

Expand Down Expand Up @@ -109,6 +109,30 @@ func main() {
}
```

### HTTP response observation

The middleware records the first final HTTP status. Informational responses can
precede it; status 101 is terminal. Writes and supported flush operations establish
an implicit 200. Streaming and string writes follow the same accounting, and the
wrapper preserves the underlying optional writer interfaces. Put this middleware
outside other response-writer middleware, so controller operations from inner
handlers reach its hooks. An outer writer that exposes controller capabilities
only through `Unwrap` can let `http.ResponseController` bypass observation; that
ordering is unsupported and can produce an incorrect recorded status. An outer
writer is compatible only when it directly delegates those capabilities. Verify
the writer order when adopting the middleware in an existing server stack.

Handled-failure snippets contain only bytes accepted by the underlying writer.
`responseAcceptedBytes` counts those bytes; buffering and HEAD responses mean this
does not prove delivery to the client. Use `WithHandled5xxMaxBodyBytes(0)` to omit
response snippets while retaining failure status and accepted-byte count.

A panic after a committed response retains that status and does not append a
fallback body. With `WithRepanic(true)`, an uncommitted panic is rethrown for outer
recovery; its future HTTP status is unknown, so the transaction omits the status
measurement. A hijacked connection without an observed status has the same
unknown-status boundary. An ordinary empty handler defaults to 200 on return.

## Branded surface

- `Duck` is the main runtime facade.
Expand Down
9 changes: 5 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
module github.com/duckbugio/duckbug-go

go 1.25.13
go 1.26.10

require (
github.com/felixge/httpsnoop v1.1.0
github.com/rs/zerolog v1.35.1
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3
go.uber.org/zap v1.28.0
Expand All @@ -13,9 +14,9 @@ require (
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
golang.org/x/net v0.60.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/text v0.42.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
google.golang.org/protobuf v1.36.11 // indirect
)
14 changes: 8 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
Expand Down Expand Up @@ -46,13 +48,13 @@ go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
Expand Down
125 changes: 17 additions & 108 deletions integrations/nethttp/middleware.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package nethttp

import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
Expand Down Expand Up @@ -66,32 +64,27 @@ func Middleware(duck *duckbug.Duck, options ...Option) func(http.Handler) http.H
ctx := pond.WithRequestContext(r.Context(), reqCtx)
r = r.WithContext(ctx)

tracker := &responseWriterTracker{
ResponseWriter: w,
statusCode: http.StatusOK,
captureResponse: config.CaptureHandled5xx,
maxResponseBytes: config.Handled5xxMaxBodyBytes,
}
tracker := newResponseWriterTracker(w, config)
tx := startTransaction(duck, r, config)
defer func() {
if recovered := recover(); recovered != nil {
tracker.statusCode = http.StatusInternalServerError
if duck != nil && config.CapturePanics {
duck.QuackRecoveredPanicContext(r.Context(), recovered, "nethttp_middleware")
}
captureTransaction(duck, r, tracker.statusCode, tx, true, config)
if config.Repanic {
captureTransaction(duck, r, tracker.responseStatus(false), tx, true, config)
panic(recovered)
}
if !tracker.wroteHeader {
http.Error(tracker, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
if !tracker.wroteHeader && !tracker.hijacked {
http.Error(tracker.writer, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
captureTransaction(duck, r, tracker.responseStatus(false), tx, true, config)
}
}()

next.ServeHTTP(tracker, r)
next.ServeHTTP(tracker.writer, r)
captureHandled5xx(duck, r, tracker, config)
captureTransaction(duck, r, tracker.statusCode, tx, false, config)
captureTransaction(duck, r, tracker.responseStatus(true), tx, false, config)
})
}
}
Expand Down Expand Up @@ -179,95 +172,6 @@ func IsInternalRequest(r *http.Request) bool {
return sdkrequest.IsInternalRequest(r)
}

type responseWriterTracker struct {
http.ResponseWriter
statusCode int
wroteHeader bool
captureResponse bool
maxResponseBytes int
responseBody strings.Builder
truncated bool
}

func (w *responseWriterTracker) WriteHeader(statusCode int) {
w.statusCode = statusCode
w.wroteHeader = true
w.ResponseWriter.WriteHeader(statusCode)
}

func (w *responseWriterTracker) Write(data []byte) (int, error) {
w.captureBody(data)
if !w.wroteHeader {
w.statusCode = http.StatusOK
}
w.wroteHeader = true
return w.ResponseWriter.Write(data)
}

func (w *responseWriterTracker) captureBody(data []byte) {
if !w.captureResponse || len(data) == 0 || w.truncated {
return
}
remaining := w.maxResponseBytes - w.responseBody.Len()
if remaining <= 0 {
w.truncated = true
return
}
if len(data) > remaining {
_, _ = w.responseBody.Write(data[:remaining])
w.truncated = true
return
}
_, _ = w.responseBody.Write(data)
}

func (w *responseWriterTracker) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := w.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, errors.New("response writer does not implement http.Hijacker")
}
return hijacker.Hijack()
}

func (w *responseWriterTracker) Flush() {
flusher, ok := w.ResponseWriter.(http.Flusher)
if !ok {
return
}
flusher.Flush()
}

func (w *responseWriterTracker) Push(target string, opts *http.PushOptions) error {
pusher, ok := w.ResponseWriter.(http.Pusher)
if !ok {
return http.ErrNotSupported
}
return pusher.Push(target, opts)
}

func (w *responseWriterTracker) ReadFrom(r io.Reader) (int64, error) {
readerFrom, ok := w.ResponseWriter.(io.ReaderFrom)
if !ok {
return io.Copy(w.ResponseWriter, r)
}
return readerFrom.ReadFrom(r)
}

func (w *responseWriterTracker) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}

func (w *responseWriterTracker) responseSnippet() string {
body := strings.TrimSpace(w.responseBody.String())
if body == "" {
return ""
}
if w.truncated {
return body + "...(truncated)"
}
return body
}

func shouldIgnoreRequest(r *http.Request, config Config) bool {
if r == nil {
return true
Expand Down Expand Up @@ -336,7 +240,9 @@ func captureTransaction(
return
}

tx.AddMeasurement("http.response.status_code", statusCode, "code")
if statusCode != 0 {
tx.AddMeasurement("http.response.status_code", statusCode, "code")
}
tx.Finish(transactionStatusFromHTTPStatus(statusCode))
duck.CaptureTransactionContext(r.Context(), tx)
}
Expand Down Expand Up @@ -365,10 +271,11 @@ func captureHandled5xx(
responseBody := tracker.responseSnippet()
responseMessage := extractResponseMessage(responseBody)
details := map[string]any{
"method": method,
"path": path,
"status": tracker.statusCode,
"userAgent": userAgent,
"method": method,
"path": path,
"status": tracker.statusCode,
"userAgent": userAgent,
"responseAcceptedBytes": tracker.acceptedBytes,
}
if responseMessage != "" {
details["responseMessage"] = responseMessage
Expand Down Expand Up @@ -427,6 +334,8 @@ func shouldCaptureTransaction(sampleRate float64, statusCode int) bool {

func transactionStatusFromHTTPStatus(statusCode int) string {
switch {
case statusCode == 0:
return "unknown_error"
case statusCode >= http.StatusInternalServerError:
return "internal_error"
case statusCode >= http.StatusBadRequest:
Expand Down
Loading
Loading