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
26 changes: 16 additions & 10 deletions handlers/baseHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ type HandlerRequest[Req any, Resp any] struct {
RespSent bool
Builder func(status int, rawResp []byte, headers map[string]string) (*Resp, error)
// Tracing fields
Span trace.Span
SpanCtx context.Context
Span trace.Span
SpanCtx context.Context
}

// Tracing methods for HandlerRequest
Expand Down Expand Up @@ -108,6 +108,11 @@ func (hr *HandlerRequest[Req, Resp]) StartChildSpan(name string, attrs map[strin
return tm.StartSpanWithAttributes(hr.SpanCtx, name, attrs)
}

// GetParser returns the RequestParser from WebFramework for tracing
func (hr HandlerRequest[Req, Resp]) GetParser() webFramework.RequestParser {
return hr.W.Parser
}

func BaseHandler[Req any, Resp any, Handler HandlerInterface[Req, Resp]](
core requestCore.RequestCoreInterface,
handler Handler,
Expand All @@ -125,7 +130,7 @@ func BaseHandler[Req any, Resp any, Handler HandlerInterface[Req, Resp]](
w = libContext.InitContextNoAuditTrail(c)
}
libContext.AddWebLogs(w, params.Title, webFramework.HandlerLogTag)

// Initialize tracing if enabled
var span trace.Span
var spanCtx context.Context
Expand All @@ -134,13 +139,13 @@ func BaseHandler[Req any, Resp any, Handler HandlerInterface[Req, Resp]](
if spanName == "" {
spanName = params.Title
}

tm := libTracing.GetGlobalTracingManager()
spanCtx, span = tm.StartSpanWithAttributes(w.Ctx, spanName, map[string]string{
"handler.title": params.Title,
"handler.path": params.Path,
})

// Add handler attributes
if span != nil && span.IsRecording() {
span.SetAttributes(
Expand All @@ -151,7 +156,7 @@ func BaseHandler[Req any, Resp any, Handler HandlerInterface[Req, Resp]](
)
}
}

trx := HandlerRequest[Req, Resp]{
Title: params.Title,
Args: args,
Expand All @@ -162,7 +167,7 @@ func BaseHandler[Req any, Resp any, Handler HandlerInterface[Req, Resp]](
}

defer Recovery(start, w, handler, params, trx, core)

// Ensure span is ended
defer func() {
if span != nil {
Expand All @@ -185,7 +190,7 @@ func BaseHandler[Req any, Resp any, Handler HandlerInterface[Req, Resp]](
trx.Header = header

var err error
trx.Response, err = handler.Simulation(trx)
trx.Response, err = libTracing.TraceFunc(handler.Simulation, trx)
if err != nil {
core.Responder().Error(trx.W, err)
return
Expand Down Expand Up @@ -215,15 +220,16 @@ func BaseHandler[Req any, Resp any, Handler HandlerInterface[Req, Resp]](
w.Parser.SetLocal("reqLog", nil)
}

errInit := handler.Initializer(trx)
var errInit error
errInit = libTracing.TraceError(handler.Initializer, trx)
webFramework.AddLog(w, webFramework.HandlerLogTag, slog.Any("initialize", errInit))
if errInit != nil {
core.Responder().Error(trx.W, errInit)
return
}

var err error
trx.Response, err = handler.Handler(trx)
trx.Response, err = libTracing.TraceFunc(handler.Handler, trx)
webFramework.AddLog(w, webFramework.HandlerLogTag, slog.Any("main-handler", err))
if err != nil {
core.Responder().Error(trx.W, err)
Expand Down
8 changes: 4 additions & 4 deletions handlers/callApi.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ func CallApiJSON[Req any, Resp any](
webFramework.AddLog(w, CallApiLogEntry, slog.Any(method, param))

param.BodyType = libCallApi.JSON
if param.Context == nil {
param.Context = w.Ctx // Set context for distributed tracing if not already set
if param.Parser == nil {
param.Parser = w.Parser // Set parser for distributed tracing if not already set
}
resp, err := libCallApi.RemoteCall(param)
if err != nil {
Expand All @@ -116,8 +116,8 @@ func CallApiForm[Req any, Resp any](
webFramework.AddLog(w, CallApiLogEntry, slog.Any(method, param))

param.BodyType = libCallApi.Form
if param.Context == nil {
param.Context = w.Ctx // Set context for distributed tracing if not already set
if param.Parser == nil {
param.Parser = w.Parser // Set parser for distributed tracing if not already set
}
resp, err := libCallApi.RemoteCall(param)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions handlers/consumeHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func (c CallArgs[Req, Resp]) Handler(req HandlerRequest[Req, Resp]) (Resp, error
Api: *req.Core.Params().GetRemoteApi(c.Api),
Method: c.Method,
Path: finalPath,
Context: req.W.Ctx, // Pass context for distributed tracing
Parser: req.W.Parser, // Pass parser for distributed tracing
},
)
if err != nil {
Expand Down Expand Up @@ -225,7 +225,7 @@ func (h *ConsumeHandlerType[Req, Resp]) Handler(req HandlerRequest[Req, Resp]) (
EnableLog: false,
Headers: headersMap,
Builder: req.Builder,
Context: req.W.Ctx, // Pass context for distributed tracing
Parser: req.W.Parser, // Pass parser for distributed tracing
})
if errCall != nil {
return req.Response, errCall
Expand Down
3 changes: 2 additions & 1 deletion handlers/recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/hmmftg/requestCore"
"github.com/hmmftg/requestCore/libError"
"github.com/hmmftg/requestCore/libTracing"
"github.com/hmmftg/requestCore/response"
"github.com/hmmftg/requestCore/status"
"github.com/hmmftg/requestCore/webFramework"
Expand All @@ -23,7 +24,7 @@ func Recovery[Req any, Resp any, Handler HandlerInterface[Req, Resp]](
) {
elapsed := time.Since(start)
webFramework.AddLogTag(w, webFramework.HandlerLogTag, slog.String("elapsed", elapsed.String()))
handler.Finalizer(trx)
libTracing.TraceVoid(handler.Finalizer, trx)
webFramework.CollectLogTags(w, webFramework.HandlerLogTag)
webFramework.CollectLogArrays(w, webFramework.HandlerLogTag)
webFramework.CollectLogTags(w, webFramework.ErrorListLogTag)
Expand Down
56 changes: 39 additions & 17 deletions libCallApi/call.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"time"

"github.com/hmmftg/requestCore/response"
"github.com/hmmftg/requestCore/webFramework"
)

type CallParam *CallParamData
Expand All @@ -24,7 +25,7 @@ type CallParamData struct {
ValidateTls bool
EnableLog bool
JsonBody any
Context context.Context `json:"-"` // Context for distributed tracing and request cancellation
Parser webFramework.RequestParser `json:"-"` // Parser for distributed tracing and request cancellation
}

func (r CallParamData) LogValue() slog.Value {
Expand All @@ -44,24 +45,27 @@ type BuilerFunc[Resp any] func(status int, rawResp []byte, headers map[string]st

type RemoteCallParamData[Req, Resp any] struct {
HttpClient *http.Client
Parameters map[string]any `json:"-"`
Headers map[string]string `json:"-"`
Api RemoteApi `json:"api"`
Timeout time.Duration `json:"-"`
Method string `json:"method"`
Path string `json:"path"`
Query string `json:"-"`
QueryStack *[]string `json:"-"`
ValidateTls bool `json:"-"`
EnableLog bool `json:"-"`
JsonBody Req `json:"body"`
BodyType RequestBodyType `json:"-"`
Builder BuilerFunc[Resp] `json:"-"`
Context context.Context `json:"-"` // Context for distributed tracing and request cancellation
Parameters map[string]any `json:"-"`
Headers map[string]string `json:"-"`
Api RemoteApi `json:"api"`
Timeout time.Duration `json:"-"`
Method string `json:"method"`
Path string `json:"path"`
Query string `json:"-"`
QueryStack *[]string `json:"-"`
ValidateTls bool `json:"-"`
EnableLog bool `json:"-"`
JsonBody Req `json:"body"`
BodyType RequestBodyType `json:"-"`
Builder BuilerFunc[Resp] `json:"-"`
Parser webFramework.RequestParser `json:"-"` // Parser for distributed tracing and request cancellation
}

func (r RemoteCallParamData[Req, Resp]) LogValue() slog.Value {
headers := maps.Clone(r.Headers)
if headers == nil {
headers = map[string]string{}
}
headers["Authorization"] = "[masked]"
return slog.GroupValue(
slog.String("api", r.Api.Name),
Expand Down Expand Up @@ -91,6 +95,13 @@ func Call[RespType any](param CallParam) CallResult[RespType] {
*param.QueryStack = nil
}
}

// Prepare context for distributed tracing / cancellation
ctx := context.Background()
if param.Parser != nil {
ctx = param.Parser.GetContext()
}

callData := CallData[RespType]{
Api: param.Api,
Path: param.Path + param.Query,
Expand All @@ -100,9 +111,11 @@ func Call[RespType any](param CallParam) CallResult[RespType] {
EnableLog: param.EnableLog,
Timeout: param.Timeout,
Req: param.JsonBody,
Context: param.Context, // Pass context for distributed tracing
Context: ctx,
LogValue: (*CallParamData)(param).LogValue(),
httpClient: param.HttpClient,
}

resp, wsResp, callResp, err := ConsumeRest(callData)
return CallResult[RespType]{resp, wsResp, callResp, err}
}
Expand All @@ -116,6 +129,13 @@ func RemoteCall[Req, Resp any](param *RemoteCallParamData[Req, Resp]) (*Resp, er
*param.QueryStack = nil
}
}

// Prepare context for distributed tracing / cancellation
ctx := context.Background()
if param.Parser != nil {
ctx = param.Parser.GetContext()
}

callData := CallData[Resp]{
Api: param.Api,
Path: param.Path + param.Query,
Expand All @@ -127,8 +147,10 @@ func RemoteCall[Req, Resp any](param *RemoteCallParamData[Req, Resp]) (*Resp, er
Req: param.JsonBody,
BodyType: param.BodyType,
Builder: param.Builder,
Context: param.Context, // Pass context for distributed tracing
Context: ctx,
LogValue: param.LogValue(),
httpClient: param.HttpClient,
}

return ConsumeRestJSON(&callData)
}
Loading
Loading