forked from mtusi2026/mtusi2026lab6
206 lines
8.3 KiB
Go
206 lines
8.3 KiB
Go
// Package telemetry exports bounded, asynchronous OTLP signals without business payloads.
|
|
package telemetry
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"go.opentelemetry.io/otel"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/codes"
|
|
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
|
|
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
|
|
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
|
otellog "go.opentelemetry.io/otel/log"
|
|
logglobal "go.opentelemetry.io/otel/log/global"
|
|
"go.opentelemetry.io/otel/metric"
|
|
"go.opentelemetry.io/otel/propagation"
|
|
sdklog "go.opentelemetry.io/otel/sdk/log"
|
|
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
|
|
"go.opentelemetry.io/otel/sdk/resource"
|
|
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
|
"go.opentelemetry.io/otel/trace"
|
|
)
|
|
|
|
const Scope = "mtusi-messenger/telemetry-v1"
|
|
|
|
var Service = "messenger-api"
|
|
var Busy atomic.Int64
|
|
var Waiting atomic.Int64
|
|
var ExportErrors atomic.Int64
|
|
var signals *Signals
|
|
|
|
type Signals struct {
|
|
Requests metric.Int64Counter
|
|
HTTPDuration metric.Float64Histogram
|
|
Jobs metric.Int64Counter
|
|
JobDuration metric.Float64Histogram
|
|
ReadyDuration metric.Float64Histogram
|
|
}
|
|
|
|
func Start(ctx context.Context, service, instance string) (func(context.Context) error, error) {
|
|
Service = service
|
|
otel.SetTextMapPropagator(propagation.TraceContext{})
|
|
attrs := []attribute.KeyValue{attribute.String("service.name", service), attribute.String("service.version", "lab6-v1"), attribute.String("service.instance.id", instance), attribute.String("deployment.environment.name", "lab")}
|
|
res := resource.NewWithAttributes("https://opentelemetry.io/schemas/1.37.0", attrs...)
|
|
traceExp, err := otlptracehttp.New(ctx, otlptracehttp.WithTimeout(2*time.Second), otlptracehttp.WithRetry(otlptracehttp.RetryConfig{Enabled: false}))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
metricExp, err := otlpmetrichttp.New(ctx, otlpmetrichttp.WithTimeout(2*time.Second), otlpmetrichttp.WithRetry(otlpmetrichttp.RetryConfig{Enabled: false}))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
logExp, err := otlploghttp.New(ctx, otlploghttp.WithTimeout(2*time.Second), otlploghttp.WithRetry(otlploghttp.RetryConfig{Enabled: false}))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res), sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), sdktrace.WithBatcher(traceExp, sdktrace.WithMaxQueueSize(256), sdktrace.WithMaxExportBatchSize(64), sdktrace.WithBatchTimeout(500*time.Millisecond), sdktrace.WithExportTimeout(2*time.Second)))
|
|
mp := sdkmetric.NewMeterProvider(sdkmetric.WithResource(res), sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExp, sdkmetric.WithInterval(2*time.Second), sdkmetric.WithTimeout(2*time.Second))))
|
|
lp := sdklog.NewLoggerProvider(sdklog.WithResource(res), sdklog.WithProcessor(sdklog.NewBatchProcessor(logExp, sdklog.WithMaxQueueSize(256), sdklog.WithExportMaxBatchSize(64), sdklog.WithExportInterval(500*time.Millisecond), sdklog.WithExportTimeout(2*time.Second))))
|
|
otel.SetTracerProvider(tp)
|
|
otel.SetMeterProvider(mp)
|
|
logglobal.SetLoggerProvider(lp)
|
|
// No exporter/network details, payloads or credentials are logged on errors.
|
|
otel.SetErrorHandler(otel.ErrorHandlerFunc(func(error) { ExportErrors.Add(1) }))
|
|
meter := otel.Meter(Scope)
|
|
s := &Signals{}
|
|
s.Requests, err = meter.Int64Counter("messenger_http_requests")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
buckets := []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 30, 60, 120}
|
|
s.HTTPDuration, _ = meter.Float64Histogram("messenger_http_duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(buckets...))
|
|
s.Jobs, _ = meter.Int64Counter("messenger_jobs_processed")
|
|
s.JobDuration, _ = meter.Float64Histogram("messenger_job_duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(buckets...))
|
|
s.ReadyDuration, _ = meter.Float64Histogram("messenger_time_to_ready", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(.1, .5, 1, 5, 10, 30, 60, 120, 300, 900, 3600, 86400))
|
|
signals = s
|
|
return func(c context.Context) error {
|
|
// Shared deadline bounds shutdown across all signals.
|
|
a := tp.Shutdown(c)
|
|
b := mp.Shutdown(c)
|
|
d := lp.Shutdown(c)
|
|
if a != nil || b != nil || d != nil {
|
|
return fmt.Errorf("telemetry shutdown incomplete")
|
|
}
|
|
return nil
|
|
}, nil
|
|
}
|
|
func Span(ctx context.Context, name string, kind trace.SpanKind, attrs ...attribute.KeyValue) (context.Context, trace.Span) {
|
|
return otel.Tracer(Scope).Start(ctx, name, trace.WithSpanKind(kind), trace.WithAttributes(attrs...))
|
|
}
|
|
func Result(span trace.Span, err error) {
|
|
if err != nil {
|
|
span.SetStatus(codes.Error, "dependency unavailable")
|
|
span.SetAttributes(attribute.Bool("error", true))
|
|
}
|
|
span.End()
|
|
}
|
|
func Inject(ctx context.Context) (string, string) {
|
|
c := propagation.MapCarrier{}
|
|
otel.GetTextMapPropagator().Inject(ctx, c)
|
|
return c.Get("traceparent"), c.Get("tracestate")
|
|
}
|
|
func Extract(ctx context.Context, parent, state string) context.Context {
|
|
return otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state})
|
|
}
|
|
|
|
type requestKey struct{}
|
|
|
|
func WithRequestID(ctx context.Context, id string) context.Context {
|
|
return context.WithValue(ctx, requestKey{}, id)
|
|
}
|
|
func RequestID(ctx context.Context) string { v, _ := ctx.Value(requestKey{}).(string); return v }
|
|
func Event(ctx context.Context, event string, fields map[string]any) {
|
|
sc := trace.SpanContextFromContext(ctx)
|
|
body := map[string]any{"timestamp": time.Now().UTC().Format(time.RFC3339Nano), "severity": "INFO", "service.name": Service, "event": event}
|
|
if sc.IsValid() {
|
|
body["trace_id"] = sc.TraceID().String()
|
|
body["span_id"] = sc.SpanID().String()
|
|
}
|
|
if id, ok := ctx.Value(requestKey{}).(string); ok {
|
|
body["request_id"] = id
|
|
}
|
|
for k, v := range fields {
|
|
body[k] = v
|
|
}
|
|
severity := otellog.SeverityInfo
|
|
if status, ok := fields["status"].(int); ok && status >= 500 {
|
|
severity = otellog.SeverityError
|
|
}
|
|
if outcome, ok := fields["outcome"].(string); ok && (outcome == "failed" || outcome == "retry" || outcome == "abandoned") {
|
|
severity = otellog.SeverityError
|
|
}
|
|
if severity == otellog.SeverityError {
|
|
body["severity"] = "ERROR"
|
|
}
|
|
encoded, _ := json.Marshal(body)
|
|
_, _ = os.Stdout.Write(append(encoded, '\n'))
|
|
var record otellog.Record
|
|
record.SetTimestamp(time.Now())
|
|
record.SetSeverity(severity)
|
|
record.SetSeverityText(body["severity"].(string))
|
|
record.SetBody(otellog.StringValue(string(encoded)))
|
|
record.AddAttributes(otellog.String("event", event))
|
|
logglobal.GetLoggerProvider().Logger(Scope).Emit(ctx, record)
|
|
}
|
|
func HTTP(ctx context.Context, method, route string, status int, elapsed time.Duration) {
|
|
if signals == nil {
|
|
return
|
|
}
|
|
a := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", fmt.Sprintf("%dxx", status/100)))
|
|
signals.Requests.Add(ctx, 1, a)
|
|
signals.HTTPDuration.Record(ctx, elapsed.Seconds(), a)
|
|
}
|
|
func Job(ctx context.Context, outcome string, d time.Duration) {
|
|
if signals == nil {
|
|
return
|
|
}
|
|
a := metric.WithAttributes(attribute.String("job_type", "attachment.process.v1"), attribute.String("outcome", outcome))
|
|
signals.Jobs.Add(ctx, 1, a)
|
|
signals.JobDuration.Record(ctx, d.Seconds(), a)
|
|
}
|
|
func Ready(ctx context.Context, d time.Duration) {
|
|
if signals != nil {
|
|
signals.ReadyDuration.Record(ctx, d.Seconds(), metric.WithAttributes(attribute.String("job_type", "attachment.process.v1")))
|
|
}
|
|
}
|
|
func Method(s string) string {
|
|
switch s {
|
|
case "GET", "POST", "DELETE", "PUT", "PATCH", "HEAD", "OPTIONS":
|
|
return s
|
|
}
|
|
return "OTHER"
|
|
}
|
|
func Route(path string) string {
|
|
switch path {
|
|
case "/health/live", "/health/ready", "/api/v1/users", "/api/v1/users/me", "/api/v1/auth/sessions", "/api/v1/auth/sessions/current", "/api/v1/chats":
|
|
return path
|
|
}
|
|
parts := strings.Split(strings.Trim(path, "/"), "/")
|
|
if len(parts) >= 4 && parts[0] == "api" && parts[1] == "v1" {
|
|
if parts[2] == "chats" {
|
|
if len(parts) == 4 {
|
|
return "/api/v1/chats/{chat_id}"
|
|
}
|
|
if len(parts) == 5 && (parts[4] == "messages" || parts[4] == "attachments") {
|
|
return "/api/v1/chats/{chat_id}/" + parts[4]
|
|
}
|
|
}
|
|
if parts[2] == "attachments" {
|
|
if len(parts) == 4 {
|
|
return "/api/v1/attachments/{attachment_id}"
|
|
}
|
|
if len(parts) == 5 && parts[4] == "content" {
|
|
return "/api/v1/attachments/{attachment_id}/content"
|
|
}
|
|
}
|
|
}
|
|
return "/unmatched"
|
|
}
|