package observability import ( "context" "fmt" "net/http" "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "github.com/prometheus/client_golang/prometheus/promhttp" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.34.0" "go.opentelemetry.io/otel/trace" "go.uber.org/zap" "google.golang.org/grpc" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) const ServiceName = "ids-svc-product" var ( grpcRequestsTotal = promauto.NewCounterVec( prometheus.CounterOpts{ Namespace: "ids", Subsystem: "product", Name: "grpc_requests_total", Help: "Total number of product service gRPC requests.", }, []string{"method", "code"}, ) grpcRequestDurationSeconds = promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: "ids", Subsystem: "product", Name: "grpc_request_duration_seconds", Help: "Product service gRPC request duration in seconds.", Buckets: prometheus.DefBuckets, }, []string{"method", "code"}, ) productsCreatedTotal = promauto.NewCounter( prometheus.CounterOpts{ Namespace: "ids", Subsystem: "product", Name: "products_created_total", Help: "Total number of products created successfully.", }, ) categoryProductListsTotal = promauto.NewCounter( prometheus.CounterOpts{ Namespace: "ids", Subsystem: "product", Name: "category_product_lists_total", Help: "Total number of successful category product list queries.", }, ) productListsTotal = promauto.NewCounter( prometheus.CounterOpts{ Namespace: "ids", Subsystem: "product", Name: "product_lists_total", Help: "Total number of successful all-product list queries.", }, ) categoryTreeListsTotal = promauto.NewCounter( prometheus.CounterOpts{ Namespace: "ids", Subsystem: "product", Name: "category_tree_lists_total", Help: "Total number of successful category tree queries.", }, ) ) // Observer wires OTLP tracing and trace-aware structured logging. type Observer struct { logger *zap.Logger tracer trace.Tracer } // New initializes OTLP export and returns a shutdown function for the tracer provider. func New(ctx context.Context, logger *zap.Logger, endpoint string, insecure bool, environment string) (*Observer, func(context.Context) error, error) { if logger == nil { logger = zap.NewNop() } if environment == "" { environment = "development" } opts := []otlptracehttp.Option{otlptracehttp.WithEndpointURL(endpoint)} if insecure { opts = append(opts, otlptracehttp.WithInsecure()) } exporter, err := otlptracehttp.New(ctx, opts...) if err != nil { return nil, nil, fmt.Errorf("create OTLP trace exporter: %w", err) } res, err := resource.New(ctx, resource.WithAttributes( semconv.ServiceName(ServiceName), attribute.String("deployment.environment", environment), ), ) if err != nil { return nil, nil, fmt.Errorf("create trace resource: %w", err) } provider := sdktrace.NewTracerProvider( sdktrace.WithBatcher(exporter), sdktrace.WithResource(res), sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), ) otel.SetTracerProvider(provider) otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator( propagation.TraceContext{}, propagation.Baggage{}, )) o := &Observer{ logger: logger, tracer: provider.Tracer(ServiceName), } return o, provider.Shutdown, nil } // NewNoop returns an observer that enriches logs and uses the global tracer provider. func NewNoop(logger *zap.Logger) *Observer { if logger == nil { logger = zap.NewNop() } return &Observer{ logger: logger, tracer: otel.Tracer(ServiceName), } } // Tracer returns the service tracer; nil-safe. func (o *Observer) Tracer() trace.Tracer { if o == nil { return otel.Tracer(ServiceName) } return o.tracer } // Logger returns a logger enriched with trace_id, span_id, and correlation_id when present. func (o *Observer) Logger(ctx context.Context) *zap.Logger { if o == nil { return zap.NewNop() } span := trace.SpanFromContext(ctx).SpanContext() logger := o.logger if logger == nil { logger = zap.NewNop() } if span.IsValid() { logger = logger.With( zap.String("trace_id", span.TraceID().String()), zap.String("span_id", span.SpanID().String()), ) } if md, ok := metadata.FromIncomingContext(ctx); ok { for _, key := range []string{"x-request-id", "correlation-id"} { if values := md.Get(key); len(values) > 0 && values[0] != "" { logger = logger.With(zap.String("correlation_id", values[0])) break } } } return logger } // UnaryServerInterceptor records access logs and request metrics for every unary RPC. func (o *Observer) UnaryServerInterceptor() grpc.UnaryServerInterceptor { return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { start := time.Now() resp, err := handler(ctx, req) duration := time.Since(start) code := status.Code(err).String() grpcRequestsTotal.WithLabelValues(info.FullMethod, code).Inc() grpcRequestDurationSeconds.WithLabelValues(info.FullMethod, code).Observe(duration.Seconds()) logger := o.Logger(ctx).With( zap.String("grpc_method", info.FullMethod), zap.String("grpc_code", code), zap.Duration("duration", duration), ) if err != nil { logger.Warn("grpc request completed", zap.Error(err)) } else { logger.Info("grpc request completed") } return resp, err } } // IncProductsCreated records a successful product creation. func IncProductsCreated() { productsCreatedTotal.Inc() } // IncCategoryProductLists records a successful category product list query. func IncCategoryProductLists() { categoryProductListsTotal.Inc() } // IncProductLists records a successful all-product list query. func IncProductLists() { productListsTotal.Inc() } // IncCategoryTreeLists records a successful category tree query. func IncCategoryTreeLists() { categoryTreeListsTotal.Inc() } // MetricsServer exposes Prometheus scrape and health endpoints. func MetricsServer(addr string, healthCheck func(context.Context) error) *http.Server { mux := http.NewServeMux() mux.Handle("/metrics", promhttp.Handler()) healthHandler := func(w http.ResponseWriter, r *http.Request) { if healthCheck != nil { ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) defer cancel() if err := healthCheck(ctx); err != nil { http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable) return } } w.WriteHeader(http.StatusOK) } mux.HandleFunc("/healthz", healthHandler) mux.HandleFunc("/readyz", healthHandler) return &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second} }