package httptraces

import (
	
	
	
	
	
	

	

	
)

const scopeName = "go.pact.im/x/traces/httptraces"

const (
	attrHTTPRequestMethod      = "http.request.method"
	attrHTTPResponseStatusCode = "http.response.status_code"
	attrHTTPRoute              = "http.route"
	attrURLPath                = "url.path"
	attrURLFull                = "url.full"
	attrURLScheme              = "url.scheme"
	attrServerAddress          = "server.address"
	attrServerPort             = "server.port"
	attrClientAddress          = "client.address"
	attrUserAgentOriginal      = "user_agent.original"
	attrNetworkProtocolVersion = "network.protocol.version"
	attrErrorType              = "error.type"
	schemeHTTP                 = "http"
	schemeHTTPS                = "https"
	errorTypePanic             = "panic"
)

// Handler is an [http.Handler] that traces incoming HTTP requests using
// [traces.Tracer].
//
// By default, incoming trace context headers are ignored so untrusted clients
// cannot forge trace IDs or force sampling; call [Handler.WithExtract] to opt
// in to header extraction on internal or trusted endpoints. The server span
// reference is propagated via [traces.NewContext], and the span is renamed
// once the route pattern is known after the wrapped handler returns. Response
// writing is wrapped with [httpsnoop.Wrap] so optional [http.ResponseWriter]
// interfaces are preserved.
type Handler struct {
	tracer   *traces.Tracer
	next     http.Handler
	filter   func(*http.Request) bool
	extract  func(get func(key string) []string) traces.SpanRef
	route    func(*http.Request) string
	spanName func(r *http.Request, route string) string
	attrs    func(*http.Request) []traces.Attr
}

var _ http.Handler = (*Handler)(nil)

// NewHandler returns a new [Handler] instance wrapping next with tr.
func ( *traces.Tracer,  http.Handler) *Handler {
	return &Handler{
		tracer:   .WithScope(scopeName),
		next:     ,
		route:    defaultRoute,
		spanName: defaultServerSpanName,
	}
}

// WithFilter returns a [Handler] that only traces requests for which f returns
// true. Filtered-out requests are passed directly to the wrapped handler
// without creating a span. If f is nil, all requests are traced.
func ( *Handler) ( func(*http.Request) bool) *Handler {
	 := *
	.filter = 
	return &
}

// WithExtract returns a [Handler] using f to extract the parent [traces.SpanRef]
// from incoming request headers (for example [traceparent.Extract]). If f is nil,
// incoming headers are ignored.
func ( *Handler) (
	 func( func( string) []string) traces.SpanRef,
) *Handler {
	 := *
	.extract = 
	return &
}

// WithRoute returns a [Handler] using f to extract the low-cardinality route
// pattern after the inner handler runs. If f is nil, it restores deriving the
// route from [http.Request.Pattern].
func ( *Handler) ( func(*http.Request) string) *Handler {
	if  == nil {
		 = defaultRoute
	}
	 := *
	.route = 
	return &
}

// WithSpanName returns a [Handler] using f to compute the final span name from
// the request and resolved route. If f is nil, it restores the default
// "METHOD route" (or "METHOD") naming.
func ( *Handler) ( func( *http.Request,  string) string) *Handler {
	if  == nil {
		 = defaultServerSpanName
	}
	 := *
	.spanName = 
	return &
}

// WithAttrs returns a [Handler] using f to attach additional start-time
// attributes for each request. If f is nil, only default attributes are added.
func ( *Handler) ( func(*http.Request) []traces.Attr) *Handler {
	 := *
	.attrs = 
	return &
}

// ServeHTTP implements the [http.Handler] interface.
func ( *Handler) ( http.ResponseWriter,  *http.Request) {
	if .filter != nil && !.filter() {
		.next.ServeHTTP(, )
		return
	}

	 := .Context()
	var  traces.SpanRef
	if .extract != nil {
		 = .extract(.Header.Values)
	}

	 := []traces.Attr{
		traces.String(attrHTTPRequestMethod, .Method),
		traces.String(attrURLPath, .URL.Path),
		traces.String(attrURLScheme, requestScheme()),
	}
	if ,  := splitHostPort(.Host);  != "" {
		 = append(, traces.String(attrServerAddress, ))
		if  > 0 {
			 = append(, traces.Int(attrServerPort, ))
		}
	}
	if  := protocolVersion(.ProtoMajor, .ProtoMinor);  != "" {
		 = append(, traces.String(attrNetworkProtocolVersion, ))
	}
	if  := .UserAgent();  != "" {
		 = append(, traces.String(attrUserAgentOriginal, ))
	}
	if ,  := splitHostPort(.RemoteAddr);  != "" {
		 = append(, traces.String(attrClientAddress, ))
	}
	if .attrs != nil {
		 = append(, .attrs()...)
	}

	 := .tracer.Start(, , traces.SpanKindServer, .Method, ...)
	 = traces.NewContext(, .Ref())
	 = .WithContext()

	 := http.StatusOK
	 := false
	 := httpsnoop.Wrap(, httpsnoop.Hooks{
		WriteHeader: func( httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc {
			return func( int) {
				if ! {
					 = 
					 = true
				}
				()
			}
		},
		Write: func( httpsnoop.WriteFunc) httpsnoop.WriteFunc {
			return func( []byte) (int, error) {
				if ! {
					 = true
				}
				return ()
			}
		},
	})

	defer func() {
		if  := recover();  != nil {
			.SetAttrs(traces.String(attrErrorType, errorTypePanic))
			.SetError(errPanic)
			.End()
			panic()
		}
	}()

	.next.ServeHTTP(, )

	 := .route()
	if  != "" {
		.SetAttrs(traces.String(attrHTTPRoute, ))
	}
	if  := .spanName(, );  != "" &&  != .Method {
		.SetName()
	}

	.SetAttrs(traces.Int(attrHTTPResponseStatusCode, ))
	if  >= http.StatusInternalServerError {
		.SetAttrs(traces.String(attrErrorType, strconv.Itoa()))
		.SetError(errors.New(http.StatusText()))
	}
	.End()
}

var errPanic = errors.New(errorTypePanic)

func ( *http.Request) string {
	if .TLS != nil {
		return schemeHTTPS
	}
	return schemeHTTP
}

func ( string) (string, int) {
	if  == "" {
		return "", 0
	}
	, ,  := net.SplitHostPort()
	if  != nil {
		return , 0
	}
	,  := strconv.Atoi()
	if  != nil ||  <= 0 {
		return , 0
	}
	return , 
}

func (,  int) string {
	switch {
	case  == 1 &&  == 0:
		return "1.0"
	case  == 1 &&  == 1:
		return "1.1"
	case  == 2 &&  == 0:
		return "2"
	case  == 3 &&  == 0:
		return "3"
	case  > 0:
		return fmt.Sprintf("%d.%d", , )
	default:
		return ""
	}
}

func ( *http.Request) string {
	return routeFromPattern(.Pattern)
}

func ( *http.Request,  string) string {
	if  == "" {
		return .Method
	}
	return .Method + " " + 
}

// routeFromPattern turns a ServeMux pattern such as "GET example.com/users/{id}"
// into "/users/{id}".
func ( string) string {
	if , ,  := strings.Cut(, " ");  {
		 = 
	}
	if  := strings.IndexByte(, '/');  >= 0 {
		return [:]
	}
	return ""
}