forked from mtusi2026/mtusi2026lab6
lab6
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -120,9 +121,18 @@ func (m JobMessage) Validate() error {
|
||||
return errors.New("created_at is required")
|
||||
}
|
||||
|
||||
if m.Traceparent != "" && !traceparentPattern.MatchString(m.Traceparent) {
|
||||
return errors.New("traceparent does not match W3C format")
|
||||
}
|
||||
if len(m.Tracestate) > 512 {
|
||||
return errors.New("tracestate is too long")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var traceparentPattern = regexp.MustCompile(`^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$`)
|
||||
|
||||
func (m JobMessage) MarshalPayload() ([]byte, error) {
|
||||
return json.Marshal(m)
|
||||
}
|
||||
|
||||
@@ -4,11 +4,15 @@ package outbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/failpoint"
|
||||
"mtusi-messenger/internal/telemetry"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
@@ -17,7 +21,9 @@ type Repository interface {
|
||||
ReleaseOutbox(ctx context.Context, id int64, reason string) error
|
||||
ReapOutboxClaims(ctx context.Context) error
|
||||
ReapExpiredLeases(ctx context.Context, limit int) (int, error)
|
||||
ReconcileQueuedJobs(ctx context.Context, olderThan time.Duration, limit int) (int, error)
|
||||
ReconcileQueuedJobs(ctx context.Context, olderThan time.Duration, limit int, traceparent, tracestate string) (int, error)
|
||||
OldestActiveJobAge(ctx context.Context) (float64, error)
|
||||
CountOverdueJobs(ctx context.Context, olderThan time.Duration) (int64, error)
|
||||
PruneOutbox(ctx context.Context, retention time.Duration) error
|
||||
OldestUnpublished(ctx context.Context) (time.Time, error)
|
||||
}
|
||||
@@ -103,7 +109,15 @@ func (r *Relay) RunOnce(ctx context.Context) (int, error) {
|
||||
|
||||
failpoint.Check("OUTBOX_AFTER_COMMIT", job.JobID)
|
||||
|
||||
if err := r.publisher.PublishConfirmed(ctx, message.RoutingKey, job); err != nil {
|
||||
publishCtx, span := telemetry.StartPublishSpan(ctx, job)
|
||||
job.Traceparent, job.Tracestate = telemetry.Inject(publishCtx)
|
||||
err = r.publisher.PublishConfirmed(publishCtx, message.RoutingKey, job)
|
||||
if err != nil {
|
||||
span.RecordError(errors.New(telemetry.Redact(err.Error())))
|
||||
span.SetStatus(codes.Error, telemetry.Redact(err.Error()))
|
||||
}
|
||||
span.End()
|
||||
if err != nil {
|
||||
_ = r.repo.ReleaseOutbox(ctx, message.ID, err.Error())
|
||||
|
||||
continue
|
||||
@@ -121,6 +135,9 @@ func (r *Relay) RunOnce(ctx context.Context) (int, error) {
|
||||
}
|
||||
|
||||
func (r *Relay) reap(ctx context.Context) {
|
||||
ctx, span := telemetry.StartRequeueSpan(ctx, "requeue")
|
||||
defer span.End()
|
||||
|
||||
if err := r.repo.ReapOutboxClaims(ctx); err != nil {
|
||||
r.log.WarnContext(ctx, "outbox claim reaper failed", slog.Any("error", err))
|
||||
}
|
||||
@@ -135,7 +152,8 @@ func (r *Relay) reap(ctx context.Context) {
|
||||
// The broker is not the source of truth. If a delivery was dead-lettered
|
||||
// or lost, the queued job has no unpublished outbox row; republish it.
|
||||
if r.config.ReconcileAfter > 0 {
|
||||
reconciled, err := r.repo.ReconcileQueuedJobs(ctx, r.config.ReconcileAfter, 100)
|
||||
traceparent, tracestate := telemetry.Inject(ctx)
|
||||
reconciled, err := r.repo.ReconcileQueuedJobs(ctx, r.config.ReconcileAfter, 100, traceparent, tracestate)
|
||||
if err != nil {
|
||||
r.log.WarnContext(ctx, "queued-job reconciliation failed", slog.Any("error", err))
|
||||
} else if reconciled > 0 {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// Package instanceid returns the stable identifier this process reports in
|
||||
// X-Instance-Id and in the telemetry resource. INSTANCE_ID wins; otherwise the
|
||||
// container hostname (short container id) is used.
|
||||
package instanceid
|
||||
|
||||
import "os"
|
||||
|
||||
func FromEnvOrHostname() string {
|
||||
if id := os.Getenv("INSTANCE_ID"); id != "" {
|
||||
return id
|
||||
}
|
||||
|
||||
if host, err := os.Hostname(); err == nil && host != "" {
|
||||
return host
|
||||
}
|
||||
|
||||
return "unknown"
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/imagecheck"
|
||||
"mtusi-messenger/internal/platform/objectstore"
|
||||
"mtusi-messenger/internal/telemetry"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -239,6 +240,7 @@ func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachm
|
||||
}
|
||||
|
||||
created.Variants = []domain.Variant{}
|
||||
telemetry.RecordJobAccepted(ctx, created.PipelineVersion)
|
||||
|
||||
return created, nil
|
||||
}
|
||||
@@ -562,6 +564,7 @@ func (s *Service) Complete(
|
||||
}
|
||||
|
||||
queued.Variants = []domain.Variant{}
|
||||
telemetry.RecordJobAccepted(ctx, queued.PipelineVersion)
|
||||
|
||||
return queued, nil
|
||||
}
|
||||
|
||||
@@ -228,7 +228,6 @@ func (s *Sweeper) deleteObject(ctx context.Context, key string) bool {
|
||||
|
||||
if !errors.Is(err, domain.ErrNotFound) {
|
||||
s.log.WarnContext(ctx, "sweep delete failed",
|
||||
slog.String("object_key", key),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/telemetry"
|
||||
)
|
||||
|
||||
// PipelineRepository owns the durable job/outbox/variant state. Queries that
|
||||
@@ -357,13 +358,15 @@ func insertOutboxTx(
|
||||
kind string,
|
||||
availableAt time.Time,
|
||||
) error {
|
||||
payload, err := domain.NewJobMessage(domain.Job{
|
||||
message := domain.NewJobMessage(domain.Job{
|
||||
ID: job.ID,
|
||||
AttachmentID: job.AttachmentID,
|
||||
PipelineVersion: job.PipelineVersion,
|
||||
Attempt: attempt,
|
||||
CreatedAt: job.CreatedAt,
|
||||
}).MarshalPayload()
|
||||
})
|
||||
message.Traceparent, message.Tracestate = telemetry.Inject(ctx)
|
||||
payload, err := message.MarshalPayload()
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal job message: %w", err)
|
||||
}
|
||||
@@ -1158,6 +1161,37 @@ func (r *PipelineRepository) ReapExpiredLeases(
|
||||
return reaped, nil
|
||||
}
|
||||
|
||||
// CountOverdueJobs returns queued/processing jobs older than the TTR objective.
|
||||
func (r *PipelineRepository) CountOverdueJobs(ctx context.Context, olderThan time.Duration) (int64, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var count int64
|
||||
if err := r.store.pool.QueryRow(ctx, `
|
||||
SELECT count(*) FROM attachment_jobs
|
||||
WHERE status IN ('queued', 'processing')
|
||||
AND created_at < now() - $1::interval`, intervalString(olderThan)).Scan(&count); err != nil {
|
||||
return 0, fmt.Errorf("count overdue jobs: %w", mapError(err))
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// OldestActiveJobAge returns the age of the oldest queued/processing job.
|
||||
// It is intentionally a small read-only query with the standard query timeout.
|
||||
func (r *PipelineRepository) OldestActiveJobAge(ctx context.Context) (float64, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var seconds float64
|
||||
if err := r.store.pool.QueryRow(ctx, `
|
||||
SELECT COALESCE(EXTRACT(EPOCH FROM (now() - min(created_at))), 0)
|
||||
FROM attachment_jobs
|
||||
WHERE status IN ('queued', 'processing')`).Scan(&seconds); err != nil {
|
||||
return 0, fmt.Errorf("oldest active job age: %w", mapError(err))
|
||||
}
|
||||
return seconds, nil
|
||||
}
|
||||
|
||||
func (r *PipelineRepository) ClaimOutbox(
|
||||
ctx context.Context,
|
||||
owner string,
|
||||
@@ -2022,6 +2056,7 @@ func (r *PipelineRepository) ReconcileQueuedJobs(
|
||||
ctx context.Context,
|
||||
olderThan time.Duration,
|
||||
limit int,
|
||||
traceparent, tracestate string,
|
||||
) (int, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
@@ -2031,7 +2066,7 @@ func (r *PipelineRepository) ReconcileQueuedJobs(
|
||||
SELECT j.job_id, j.attachment_id, j.pipeline_version, j.attempt, j.created_at
|
||||
FROM attachment_jobs j
|
||||
WHERE j.status = 'queued'
|
||||
AND j.available_at < now() - $1::interval
|
||||
AND j.available_at <= now() - $1::interval
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM outbox_messages o
|
||||
WHERE o.job_id = j.job_id AND o.published_at IS NULL
|
||||
@@ -2049,10 +2084,15 @@ func (r *PipelineRepository) ReconcileQueuedJobs(
|
||||
'attachment_id', attachment_id,
|
||||
'pipeline_version', pipeline_version,
|
||||
'attempt', attempt,
|
||||
'created_at', created_at),
|
||||
'created_at', created_at)
|
||||
|| CASE
|
||||
WHEN $4::text = '' THEN '{}'::jsonb
|
||||
WHEN COALESCE($5::text, '') = '' THEN jsonb_build_object('traceparent', $4::text)
|
||||
ELSE jsonb_build_object('traceparent', $4::text, 'tracestate', $5::text)
|
||||
END,
|
||||
now()
|
||||
FROM lost`,
|
||||
intervalString(olderThan), limit, defaultRoutingKey)
|
||||
intervalString(olderThan), limit, defaultRoutingKey, traceparent, tracestate)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("reconcile queued jobs: %w", mapError(err))
|
||||
}
|
||||
|
||||
@@ -518,7 +518,7 @@ func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() {
|
||||
s.Require().Len(claimed, 1)
|
||||
s.Require().NoError(repo.MarkPublished(s.T().Context(), []int64{claimed[0].ID}))
|
||||
|
||||
reconciled, err := repo.ReconcileQueuedJobs(s.T().Context(), 0, 10)
|
||||
reconciled, err := repo.ReconcileQueuedJobs(s.T().Context(), 0, 10, "", "")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(1, reconciled)
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ func (r *SessionRepository) Credentials(ctx context.Context, username string) (d
|
||||
row, err := r.store.queries.GetUserByUsername(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.UserCredentials{}, fmt.Errorf("%w: username %q", domain.ErrUnauthenticated, username)
|
||||
return domain.UserCredentials{}, fmt.Errorf("%w", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
return domain.UserCredentials{}, fmt.Errorf("load credentials: %w", mapError(err))
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
@@ -24,7 +25,25 @@ type Store struct {
|
||||
pipeline *PipelineRepository
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration) (*Store, error) {
|
||||
type options struct {
|
||||
queryTracer pgx.QueryTracer
|
||||
}
|
||||
|
||||
// Option customizes the PostgreSQL store without leaking telemetry into the
|
||||
// storage package's public API.
|
||||
type Option func(*options)
|
||||
|
||||
// WithQueryTracer installs a pgx tracer (nil means no tracing).
|
||||
func WithQueryTracer(tracer pgx.QueryTracer) Option {
|
||||
return func(o *options) { o.queryTracer = tracer }
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration, opts ...Option) (*Store, error) {
|
||||
options := options{}
|
||||
for _, opt := range opts {
|
||||
opt(&options)
|
||||
}
|
||||
|
||||
cfg, err := normalize(cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("normalize database config: %w", err)
|
||||
@@ -40,6 +59,9 @@ func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration)
|
||||
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
|
||||
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
|
||||
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
|
||||
if options.queryTracer != nil {
|
||||
poolCfg.ConnConfig.Tracer = options.queryTracer
|
||||
}
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
@@ -82,13 +104,19 @@ func (s *Store) Sessions() *SessionRepository { return s.sessions }
|
||||
func (s *Store) Pipeline() *PipelineRepository { return s.pipeline }
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := s.pool.Ping(pingCtx); err != nil {
|
||||
return fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// PoolStats exposes a point-in-time pgxpool snapshot for telemetry callbacks.
|
||||
func (s *Store) PoolStats() *pgxpool.Stat { return s.pool.Stat() }
|
||||
|
||||
func (s *Store) Close() { s.pool.Close() }
|
||||
|
||||
// sweepLockKey is a process-independent constant: every replica contends for the
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/exaring/otelpgx"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
// NewPGXTracer returns a pgx tracer that records database spans without SQL
|
||||
// text or connection details (those can contain identifiers and DSNs).
|
||||
func NewPGXTracer() pgx.QueryTracer {
|
||||
return otelpgx.NewTracer(
|
||||
otelpgx.WithTracerProvider(otel.GetTracerProvider()),
|
||||
otelpgx.WithDisableSQLStatementInAttributes(),
|
||||
otelpgx.WithDisableConnectionDetailsInAttributes(),
|
||||
)
|
||||
}
|
||||
|
||||
// RegisterDBPool exposes pgxpool gauges. pgxpool has no current "waiting"
|
||||
// counter; EmptyAcquireCount/WaitTime are the observable contention signal.
|
||||
func RegisterDBPool(stats func() *pgxpool.Stat) error {
|
||||
initMetrics()
|
||||
_, err := otel.Meter("messenger").RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
||||
s := stats()
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
o.ObserveInt64(dbUsed, int64(s.AcquiredConns()))
|
||||
o.ObserveInt64(dbIdle, int64(s.IdleConns()))
|
||||
o.ObserveInt64(dbMax, int64(s.MaxConns()))
|
||||
o.ObserveInt64(dbEmptyAcquire, s.EmptyAcquireCount())
|
||||
o.ObserveFloat64(dbEmptyWait, s.EmptyAcquireWaitTime().Seconds())
|
||||
return nil
|
||||
}, dbUsed, dbIdle, dbMax, dbEmptyAcquire, dbEmptyWait)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
var traceparentPattern = regexp.MustCompile(`^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$`)
|
||||
|
||||
// ValidTraceparent reports whether a broker-carried traceparent matches the
|
||||
// closed schema before it is trusted as a parent context.
|
||||
func ValidTraceparent(value string) bool {
|
||||
return value == "" || (len(value) <= 512 && traceparentPattern.MatchString(value))
|
||||
}
|
||||
|
||||
// Inject serializes the current span context for a durable outbox payload.
|
||||
func Inject(ctx context.Context) (traceparent, tracestate string) {
|
||||
carrier := propagation.MapCarrier{}
|
||||
otel.GetTextMapPropagator().Inject(ctx, carrier)
|
||||
tracestate = carrier["tracestate"]
|
||||
if len(tracestate) > 512 {
|
||||
tracestate = ""
|
||||
}
|
||||
return carrier["traceparent"], tracestate
|
||||
}
|
||||
|
||||
// Extract restores a parent context from a broker payload. Invalid values are
|
||||
// ignored; the caller still gets a usable context.
|
||||
func Extract(ctx context.Context, traceparent, tracestate string) context.Context {
|
||||
if !ValidTraceparent(traceparent) || len(tracestate) > 512 {
|
||||
return ctx
|
||||
}
|
||||
carrier := propagation.MapCarrier{"traceparent": traceparent}
|
||||
if tracestate != "" {
|
||||
carrier["tracestate"] = tracestate
|
||||
}
|
||||
return otel.GetTextMapPropagator().Extract(ctx, carrier)
|
||||
}
|
||||
|
||||
// StartPublishSpan starts the producer span for an outbox publication. The
|
||||
// returned context carries the span that must be injected into the message.
|
||||
func StartPublishSpan(ctx context.Context, message domain.JobMessage) (context.Context, trace.Span) {
|
||||
parent := Extract(ctx, message.Traceparent, message.Tracestate)
|
||||
return otel.Tracer("messenger/queue").Start(parent, "job.publish",
|
||||
trace.WithSpanKind(trace.SpanKindProducer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("messaging.system", "rabbitmq"),
|
||||
attribute.String("messaging.operation", "publish"),
|
||||
attribute.String("messaging.destination.name", message.Type),
|
||||
attribute.String("job.id", message.JobID.String()),
|
||||
attribute.String("job.type", message.Type),
|
||||
attribute.Int("job.attempt", message.Attempt),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// StartConsumerSpan starts the worker span as a child of the publish span.
|
||||
func StartConsumerSpan(ctx context.Context, message domain.JobMessage) (context.Context, trace.Span) {
|
||||
parent := Extract(ctx, message.Traceparent, message.Tracestate)
|
||||
return otel.Tracer("messenger/worker").Start(parent, "job.process",
|
||||
trace.WithSpanKind(trace.SpanKindConsumer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("messaging.system", "rabbitmq"),
|
||||
attribute.String("messaging.operation", "process"),
|
||||
attribute.String("messaging.destination.name", message.Type),
|
||||
attribute.String("job.id", message.JobID.String()),
|
||||
attribute.String("job.type", message.Type),
|
||||
attribute.Int("job.attempt", message.Attempt),
|
||||
attribute.Int("pipeline.version", message.PipelineVersion),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// StartRequeueSpan covers the relay's lease reaper / reconciliation path.
|
||||
func StartRequeueSpan(ctx context.Context, operation string) (context.Context, trace.Span) {
|
||||
return otel.Tracer("messenger/relay").Start(ctx, "job."+operation,
|
||||
trace.WithAttributes(attribute.String("job.operation", operation)),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"regexp"
|
||||
|
||||
"go.opentelemetry.io/contrib/bridges/otelslog"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi-messenger/internal/platform/instanceid"
|
||||
)
|
||||
|
||||
var (
|
||||
allowKeys = map[string]struct{}{
|
||||
"event": {}, "operation": {}, "route": {}, "method": {}, "status": {},
|
||||
"status_class": {}, "duration": {}, "error_code": {}, "job_type": {},
|
||||
"outcome": {}, "attempt": {}, "pipeline_version": {}, "queue": {},
|
||||
"count": {}, "bytes": {}, "size": {}, "job_id": {},
|
||||
"service.name": {}, "service.instance.id": {},
|
||||
"deployment.environment.name": {}, "trace_id": {}, "span_id": {},
|
||||
"request_id": {}, "error": {},
|
||||
}
|
||||
requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
|
||||
redactPatterns = []*regexp.Regexp{
|
||||
regexp.MustCompile(`(?i)(X-Amz-(?:Signature|Credential|Security-Token)=)[^&\s"]+`),
|
||||
regexp.MustCompile(`(?i)(password|passwd|secret|token|authorization)=([^&\s"]+)`),
|
||||
regexp.MustCompile(`://[^/\s:@]+:[^@\s]+@`),
|
||||
regexp.MustCompile(`(?i)\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b`),
|
||||
regexp.MustCompile(`\b(?:attachments|staging|variants)/[^\s"']+`),
|
||||
}
|
||||
)
|
||||
|
||||
// WrapLogger returns a logger that writes sanitized JSON to stdout and, when
|
||||
// configured, also emits OTLP log records. The sanitizer is the boundary that
|
||||
// prevents raw paths, filenames, user ids and credentials from reaching any
|
||||
// telemetry backend.
|
||||
func WrapLogger(base *slog.Logger, serviceName string, minLevel slog.Level) *slog.Logger {
|
||||
if base == nil {
|
||||
base = slog.Default()
|
||||
}
|
||||
|
||||
var otelHandler slog.Handler
|
||||
if provider := GlobalLoggerProvider(); provider != nil {
|
||||
otelHandler = otelslog.NewHandler("messenger", otelslog.WithLoggerProvider(provider))
|
||||
}
|
||||
|
||||
return slog.New(&sanitizeHandler{
|
||||
inner: &fanoutHandler{handlers: []slog.Handler{base.Handler(), otelHandler}},
|
||||
service: serviceName,
|
||||
instance: instanceid.FromEnvOrHostname(),
|
||||
minLevel: minLevel,
|
||||
})
|
||||
}
|
||||
|
||||
type fanoutHandler struct {
|
||||
handlers []slog.Handler
|
||||
}
|
||||
|
||||
func (h *fanoutHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
||||
for _, handler := range h.handlers {
|
||||
if handler != nil && handler.Enabled(ctx, level) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *fanoutHandler) Handle(ctx context.Context, record slog.Record) error {
|
||||
for _, handler := range h.handlers {
|
||||
if handler == nil {
|
||||
continue
|
||||
}
|
||||
if err := handler.Handle(ctx, record.Clone()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *fanoutHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
next := &fanoutHandler{handlers: make([]slog.Handler, 0, len(h.handlers))}
|
||||
for _, handler := range h.handlers {
|
||||
if handler == nil {
|
||||
next.handlers = append(next.handlers, nil)
|
||||
continue
|
||||
}
|
||||
next.handlers = append(next.handlers, handler.WithAttrs(attrs))
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
func (h *fanoutHandler) WithGroup(name string) slog.Handler {
|
||||
next := &fanoutHandler{handlers: make([]slog.Handler, 0, len(h.handlers))}
|
||||
for _, handler := range h.handlers {
|
||||
if handler == nil {
|
||||
next.handlers = append(next.handlers, nil)
|
||||
continue
|
||||
}
|
||||
next.handlers = append(next.handlers, handler.WithGroup(name))
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
type sanitizeHandler struct {
|
||||
inner slog.Handler
|
||||
service string
|
||||
instance string
|
||||
minLevel slog.Level
|
||||
}
|
||||
|
||||
func (h *sanitizeHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
||||
return level >= h.minLevel && h.inner.Enabled(ctx, level)
|
||||
}
|
||||
|
||||
func (h *sanitizeHandler) Handle(ctx context.Context, record slog.Record) error {
|
||||
sanitized := slog.NewRecord(record.Time, record.Level, sanitizeText(record.Message), record.PC)
|
||||
|
||||
seenEvent := false
|
||||
record.Attrs(func(attr slog.Attr) bool {
|
||||
if attr.Key == "event" {
|
||||
seenEvent = true
|
||||
}
|
||||
if clean, ok := sanitizeAttr(attr); ok {
|
||||
sanitized.AddAttrs(clean)
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
if !seenEvent {
|
||||
event := sanitizeText(record.Message)
|
||||
if event == "" {
|
||||
event = "log"
|
||||
}
|
||||
sanitized.AddAttrs(slog.String("event", event))
|
||||
}
|
||||
if h.service != "" {
|
||||
sanitized.AddAttrs(slog.String("service.name", h.service))
|
||||
}
|
||||
if h.instance != "" {
|
||||
sanitized.AddAttrs(slog.String("service.instance.id", h.instance))
|
||||
}
|
||||
if spanContext := trace.SpanContextFromContext(ctx); spanContext.IsValid() {
|
||||
sanitized.AddAttrs(
|
||||
slog.String("trace_id", spanContext.TraceID().String()),
|
||||
slog.String("span_id", spanContext.SpanID().String()),
|
||||
)
|
||||
}
|
||||
|
||||
return h.inner.Handle(ctx, sanitized)
|
||||
}
|
||||
|
||||
func (h *sanitizeHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
clean := make([]slog.Attr, 0, len(attrs))
|
||||
for _, attr := range attrs {
|
||||
if value, ok := sanitizeAttr(attr); ok {
|
||||
clean = append(clean, value)
|
||||
}
|
||||
}
|
||||
return &sanitizeHandler{inner: h.inner.WithAttrs(clean), service: h.service, instance: h.instance, minLevel: h.minLevel}
|
||||
}
|
||||
|
||||
func (h *sanitizeHandler) WithGroup(name string) slog.Handler {
|
||||
return &sanitizeHandler{inner: h.inner.WithGroup(name), service: h.service, instance: h.instance, minLevel: h.minLevel}
|
||||
}
|
||||
|
||||
func sanitizeAttr(attr slog.Attr) (slog.Attr, bool) {
|
||||
if _, ok := allowKeys[attr.Key]; !ok {
|
||||
return slog.Attr{}, false
|
||||
}
|
||||
|
||||
value := attr.Value.Resolve()
|
||||
switch attr.Key {
|
||||
case "error":
|
||||
return slog.String("error", Redact(value.String())), true
|
||||
case "request_id":
|
||||
id := value.String()
|
||||
if !requestIDPattern.MatchString(id) {
|
||||
id = "invalid"
|
||||
}
|
||||
return slog.String("request_id", id), true
|
||||
}
|
||||
|
||||
if value.Kind() == slog.KindGroup {
|
||||
return slog.Attr{}, false
|
||||
}
|
||||
if value.Kind() == slog.KindString {
|
||||
return slog.String(attr.Key, sanitizeText(value.String())), true
|
||||
}
|
||||
return slog.Attr{Key: attr.Key, Value: value}, true
|
||||
}
|
||||
|
||||
func sanitizeText(value string) string {
|
||||
return truncate(Redact(value), 1024)
|
||||
}
|
||||
|
||||
// Redact removes credentials, signed-URL parameters, UUIDs and object keys from
|
||||
// free-form error text before it reaches stdout, logs or trace exception events.
|
||||
func Redact(value string) string {
|
||||
for _, pattern := range redactPatterns {
|
||||
value = pattern.ReplaceAllString(value, "$1***")
|
||||
}
|
||||
return truncate(value, 1024)
|
||||
}
|
||||
|
||||
func truncate(value string, limit int) string {
|
||||
if len(value) <= limit {
|
||||
return value
|
||||
}
|
||||
return value[:limit] + "..."
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type captureHandler struct {
|
||||
attrs []slog.Attr
|
||||
}
|
||||
|
||||
func (h *captureHandler) Enabled(context.Context, slog.Level) bool { return true }
|
||||
func (h *captureHandler) Handle(_ context.Context, record slog.Record) error {
|
||||
record.Attrs(func(attr slog.Attr) bool {
|
||||
h.attrs = append(h.attrs, attr)
|
||||
return true
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *captureHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
return &captureHandler{attrs: append(h.attrs, attrs...)}
|
||||
}
|
||||
func (h *captureHandler) WithGroup(string) slog.Handler { return h }
|
||||
|
||||
func TestSanitizerDropsIdentifiersAndRedactsErrors(t *testing.T) {
|
||||
capture := &captureHandler{}
|
||||
handler := &sanitizeHandler{inner: capture, service: "messenger-api", instance: "instance-1", minLevel: slog.LevelDebug}
|
||||
record := slog.NewRecord(time.Now(), slog.LevelInfo, "request handled", 0)
|
||||
record.AddAttrs(
|
||||
slog.String("event", "http.request.completed"),
|
||||
slog.String("path", "/api/v1/chats/33333333-3333-4333-8333-333333333333/messages"),
|
||||
slog.String("query", "filename=secret.png"),
|
||||
slog.String("user_id", "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"),
|
||||
slog.String("object_key", "attachments/chat/attachment/original"),
|
||||
slog.String("error", `parse "postgres://user:pass@db:5432/x": X-Amz-Signature=abc attachments/33333333-3333-4333-8333-333333333333/44444444-4444-4444-8444-444444444444/original`),
|
||||
slog.String("request_id", "bad request id with spaces"),
|
||||
)
|
||||
if err := handler.Handle(context.Background(), record); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
seen := map[string]string{}
|
||||
for _, attr := range capture.attrs {
|
||||
seen[attr.Key] = attr.Value.String()
|
||||
}
|
||||
for _, forbidden := range []string{"path", "query", "user_id", "object_key"} {
|
||||
if _, ok := seen[forbidden]; ok {
|
||||
t.Fatalf("forbidden attribute %q was exported", forbidden)
|
||||
}
|
||||
}
|
||||
if strings.Contains(seen["error"], "pass") || strings.Contains(seen["error"], "abc") {
|
||||
t.Fatalf("error was not redacted: %q", seen["error"])
|
||||
}
|
||||
if strings.Contains(seen["error"], "33333333") || strings.Contains(seen["error"], "attachments/") {
|
||||
t.Fatalf("object key/uuid was not redacted: %q", seen["error"])
|
||||
}
|
||||
if seen["request_id"] != "invalid" {
|
||||
t.Fatalf("request_id was not normalized: %q", seen["request_id"])
|
||||
}
|
||||
if seen["service.name"] != "messenger-api" || seen["service.instance.id"] != "instance-1" {
|
||||
t.Fatalf("service attributes missing: %#v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidTraceparent(t *testing.T) {
|
||||
if !ValidTraceparent("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01") {
|
||||
t.Fatal("valid traceparent rejected")
|
||||
}
|
||||
if ValidTraceparent("not-a-traceparent") || ValidTraceparent("00-X") {
|
||||
t.Fatal("invalid traceparent accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectDropsOversizedTracestate(t *testing.T) {
|
||||
otel.SetTextMapPropagator(propagation.TraceContext{})
|
||||
ts, err := trace.ParseTraceState("a=" + strings.Repeat("a", 180) + ",b=" + strings.Repeat("b", 180) + ",c=" + strings.Repeat("c", 180))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sc := trace.NewSpanContext(trace.SpanContextConfig{
|
||||
TraceID: trace.TraceID{1},
|
||||
SpanID: trace.SpanID{1},
|
||||
TraceState: ts,
|
||||
})
|
||||
traceparent, tracestate := Inject(trace.ContextWithSpanContext(context.Background(), sc))
|
||||
if traceparent == "" {
|
||||
t.Fatal("traceparent missing")
|
||||
}
|
||||
if tracestate != "" {
|
||||
t.Fatalf("oversized tracestate was persisted: %d bytes", len(tracestate))
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectPreservesValidTracestate(t *testing.T) {
|
||||
otel.SetTextMapPropagator(propagation.TraceContext{})
|
||||
small, err := trace.ParseTraceState("vendor=abc123")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sc := trace.NewSpanContext(trace.SpanContextConfig{
|
||||
TraceID: trace.TraceID{1},
|
||||
SpanID: trace.SpanID{1},
|
||||
TraceState: small,
|
||||
})
|
||||
_, kept := Inject(trace.ContextWithSpanContext(context.Background(), sc))
|
||||
if kept != "vendor=abc123" {
|
||||
t.Fatalf("valid tracestate dropped: %q", kept)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
var (
|
||||
metricsOnce sync.Once
|
||||
|
||||
httpRequests metric.Int64Counter
|
||||
httpDuration metric.Float64Histogram
|
||||
jobsProcessed metric.Int64Counter
|
||||
jobDuration metric.Float64Histogram
|
||||
jobsAccepted metric.Int64Counter
|
||||
timeToReady metric.Float64Histogram
|
||||
jobsReadyInBudget metric.Int64Counter
|
||||
workerBusy metric.Int64ObservableGauge
|
||||
workerCapacity metric.Int64ObservableGauge
|
||||
dbUsed metric.Int64ObservableGauge
|
||||
dbIdle metric.Int64ObservableGauge
|
||||
dbMax metric.Int64ObservableGauge
|
||||
dbEmptyAcquire metric.Int64ObservableCounter
|
||||
dbEmptyWait metric.Float64ObservableCounter
|
||||
processCPU metric.Float64ObservableCounter
|
||||
processMemory metric.Int64ObservableGauge
|
||||
processMemLimit metric.Int64ObservableGauge
|
||||
oldestJobAge metric.Float64ObservableGauge
|
||||
oldestOutboxAge metric.Float64ObservableGauge
|
||||
jobsOverdue metric.Int64ObservableGauge
|
||||
)
|
||||
|
||||
func initMetrics() {
|
||||
metricsOnce.Do(func() {
|
||||
meter := otel.Meter("messenger")
|
||||
|
||||
httpRequests, _ = meter.Int64Counter("messenger.http.server.requests",
|
||||
metric.WithDescription("HTTP requests by method, route template and status class"))
|
||||
httpDuration, _ = meter.Float64Histogram("http.server.request.duration",
|
||||
metric.WithDescription("HTTP server request duration"),
|
||||
metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10))
|
||||
jobsProcessed, _ = meter.Int64Counter("messenger.jobs.processed",
|
||||
metric.WithDescription("Attachment job attempts by outcome"))
|
||||
jobDuration, _ = meter.Float64Histogram("messenger.job.duration",
|
||||
metric.WithDescription("Attachment job processing duration"),
|
||||
metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120))
|
||||
jobsAccepted, _ = meter.Int64Counter("messenger.jobs.accepted",
|
||||
metric.WithDescription("Durable attachment jobs accepted with 202"))
|
||||
timeToReady, _ = meter.Float64Histogram("messenger.job.time_to_ready",
|
||||
metric.WithDescription("Time from durable acceptance to ready"),
|
||||
metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(1, 2.5, 5, 10, 20, 30, 60, 120, 300))
|
||||
jobsReadyInBudget, _ = meter.Int64Counter("messenger.jobs.ready_within_budget",
|
||||
metric.WithDescription("Jobs ready within the 30s TTR objective"))
|
||||
workerBusy, _ = meter.Int64ObservableGauge("messenger.worker.busy",
|
||||
metric.WithDescription("Worker slots currently processing a job"))
|
||||
workerCapacity, _ = meter.Int64ObservableGauge("messenger.worker.capacity",
|
||||
metric.WithDescription("Configured worker concurrency"))
|
||||
dbUsed, _ = meter.Int64ObservableGauge("messenger.db.pool.used")
|
||||
dbIdle, _ = meter.Int64ObservableGauge("messenger.db.pool.idle")
|
||||
dbMax, _ = meter.Int64ObservableGauge("messenger.db.pool.max")
|
||||
dbEmptyAcquire, _ = meter.Int64ObservableCounter("messenger.db.pool.empty_acquire",
|
||||
metric.WithDescription("Acquisitions that had to wait for a free connection"))
|
||||
dbEmptyWait, _ = meter.Float64ObservableCounter("messenger.db.pool.empty_acquire_wait_seconds",
|
||||
metric.WithDescription("Cumulative wait time for empty pool acquisitions"),
|
||||
metric.WithUnit("s"))
|
||||
processCPU, _ = meter.Float64ObservableCounter("messenger.process.cpu_seconds",
|
||||
metric.WithDescription("Cumulative process CPU time from cgroup or /proc"),
|
||||
metric.WithUnit("s"))
|
||||
processMemory, _ = meter.Int64ObservableGauge("messenger.process.memory_usage_bytes",
|
||||
metric.WithDescription("Resident/current memory of this container"),
|
||||
metric.WithUnit("By"))
|
||||
processMemLimit, _ = meter.Int64ObservableGauge("messenger.process.memory_limit_bytes",
|
||||
metric.WithDescription("Container memory limit, 0 when unknown"),
|
||||
metric.WithUnit("By"))
|
||||
oldestJobAge, _ = meter.Float64ObservableGauge("messenger.queue.oldest_job_age",
|
||||
metric.WithDescription("Age of the oldest queued or processing job"),
|
||||
metric.WithUnit("s"))
|
||||
oldestOutboxAge, _ = meter.Float64ObservableGauge("messenger.outbox.oldest_unpublished_age",
|
||||
metric.WithDescription("Age of the oldest unpublished outbox intent"),
|
||||
metric.WithUnit("s"))
|
||||
jobsOverdue, _ = meter.Int64ObservableGauge("messenger.jobs.overdue",
|
||||
metric.WithDescription("Queued/processing jobs older than the 30s TTR objective"))
|
||||
})
|
||||
}
|
||||
|
||||
// RecordHTTP records one completed server request. route must be an OpenAPI
|
||||
// template, never a raw path.
|
||||
func RecordHTTP(ctx context.Context, method, route string, status int, duration time.Duration) {
|
||||
initMetrics()
|
||||
class := statusClass(status)
|
||||
attrs := metric.WithAttributes(
|
||||
attribute.String("http.request.method", method),
|
||||
attribute.String("http.route", route),
|
||||
attribute.Int("http.response.status_code", status),
|
||||
attribute.String("http.response.status_class", class),
|
||||
)
|
||||
httpRequests.Add(ctx, 1, attrs)
|
||||
httpDuration.Record(ctx, duration.Seconds(), attrs)
|
||||
}
|
||||
|
||||
// RecordJobAccepted counts a durable 202 acceptance.
|
||||
func RecordJobAccepted(ctx context.Context, pipelineVersion int) {
|
||||
initMetrics()
|
||||
jobsAccepted.Add(ctx, 1, metric.WithAttributes(attribute.Int("pipeline.version", pipelineVersion)))
|
||||
}
|
||||
|
||||
// RecordJobAttempt records one processing attempt.
|
||||
func RecordJobAttempt(ctx context.Context, jobType, outcome string, duration time.Duration) {
|
||||
initMetrics()
|
||||
attrs := metric.WithAttributes(
|
||||
attribute.String("job.type", jobType),
|
||||
attribute.String("outcome", outcome),
|
||||
)
|
||||
jobsProcessed.Add(ctx, 1, attrs)
|
||||
jobDuration.Record(ctx, duration.Seconds(), attrs)
|
||||
}
|
||||
|
||||
// RecordJobReady records a terminal ready result and its time-to-ready.
|
||||
func RecordJobReady(ctx context.Context, pipelineVersion int, duration time.Duration) {
|
||||
initMetrics()
|
||||
attrs := metric.WithAttributes(attribute.Int("pipeline.version", pipelineVersion))
|
||||
timeToReady.Record(ctx, duration.Seconds(), attrs)
|
||||
if duration <= 30*time.Second {
|
||||
jobsReadyInBudget.Add(ctx, 1, attrs)
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterWorkerMetrics exposes the worker's in-flight slots and capacity.
|
||||
// RegisterRelayMetrics exposes durable backlog age gauges computed in the relay.
|
||||
func RegisterRelayMetrics(oldestJob func(context.Context) (float64, error), oldestOutbox func(context.Context) (time.Duration, error), overdue func(context.Context) (int64, error)) error {
|
||||
initMetrics()
|
||||
_, err := otel.Meter("messenger").RegisterCallback(func(ctx context.Context, o metric.Observer) error {
|
||||
if oldestJob != nil {
|
||||
if seconds, err := oldestJob(ctx); err == nil {
|
||||
o.ObserveFloat64(oldestJobAge, seconds)
|
||||
}
|
||||
}
|
||||
if oldestOutbox != nil {
|
||||
if age, err := oldestOutbox(ctx); err == nil {
|
||||
o.ObserveFloat64(oldestOutboxAge, age.Seconds())
|
||||
}
|
||||
}
|
||||
if overdue != nil {
|
||||
if count, err := overdue(ctx); err == nil {
|
||||
o.ObserveInt64(jobsOverdue, count)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}, oldestJobAge, oldestOutboxAge, jobsOverdue)
|
||||
return err
|
||||
}
|
||||
|
||||
func RegisterWorkerMetrics(busy func() int64, capacity int64) error {
|
||||
initMetrics()
|
||||
_, err := otel.Meter("messenger").RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
||||
o.ObserveInt64(workerBusy, busy())
|
||||
o.ObserveInt64(workerCapacity, capacity)
|
||||
return nil
|
||||
}, workerBusy, workerCapacity)
|
||||
return err
|
||||
}
|
||||
|
||||
func statusClass(status int) string {
|
||||
if status < 100 || status > 599 {
|
||||
return "unknown"
|
||||
}
|
||||
return strconv.Itoa(status/100) + "xx"
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi-messenger/internal/platform/objectstore"
|
||||
)
|
||||
|
||||
type tracedStore struct {
|
||||
inner objectstore.Store
|
||||
}
|
||||
|
||||
// WrapStore adds S3 client spans without recording object keys (keys contain
|
||||
// chat_id) or presigned URLs.
|
||||
func WrapStore(inner objectstore.Store) objectstore.Store {
|
||||
if inner == nil {
|
||||
return nil
|
||||
}
|
||||
return &tracedStore{inner: inner}
|
||||
}
|
||||
|
||||
func (s *tracedStore) start(ctx context.Context, operation string) (context.Context, trace.Span) {
|
||||
return otel.Tracer("messenger/s3").Start(ctx, "S3."+operation,
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(
|
||||
attribute.String("rpc.system", "aws.s3"),
|
||||
attribute.String("rpc.service", "S3"),
|
||||
attribute.String("rpc.method", operation),
|
||||
attribute.String("aws.s3.operation", operation),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
func (s *tracedStore) Ping(ctx context.Context) error {
|
||||
ctx, span := s.start(ctx, "Ping")
|
||||
defer span.End()
|
||||
return s.inner.Ping(ctx)
|
||||
}
|
||||
|
||||
func (s *tracedStore) Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string, metadata map[string]string) error {
|
||||
ctx, span := s.start(ctx, "PutObject")
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.Int64("aws.s3.object.size", size))
|
||||
return s.inner.Put(ctx, key, body, size, contentType, metadata)
|
||||
}
|
||||
|
||||
type spanReadCloser struct {
|
||||
inner io.ReadCloser
|
||||
span trace.Span
|
||||
}
|
||||
|
||||
func (r *spanReadCloser) Read(p []byte) (int, error) { return r.inner.Read(p) }
|
||||
func (r *spanReadCloser) Close() error {
|
||||
err := r.inner.Close()
|
||||
r.span.End()
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *tracedStore) Open(ctx context.Context, key string) (io.ReadCloser, objectstore.Object, error) {
|
||||
ctx, span := s.start(ctx, "GetObject")
|
||||
body, object, err := s.inner.Open(ctx, key)
|
||||
if err != nil {
|
||||
span.RecordError(errors.New(Redact(err.Error())))
|
||||
span.End()
|
||||
return nil, object, err
|
||||
}
|
||||
span.SetAttributes(attribute.Int64("aws.s3.object.size", object.Size))
|
||||
return &spanReadCloser{inner: body, span: span}, object, nil
|
||||
}
|
||||
|
||||
func (s *tracedStore) Head(ctx context.Context, key string) (objectstore.Object, error) {
|
||||
ctx, span := s.start(ctx, "HeadObject")
|
||||
defer span.End()
|
||||
return s.inner.Head(ctx, key)
|
||||
}
|
||||
|
||||
func (s *tracedStore) Copy(ctx context.Context, src, dst, contentType string, metadata map[string]string) error {
|
||||
ctx, span := s.start(ctx, "CopyObject")
|
||||
defer span.End()
|
||||
return s.inner.Copy(ctx, src, dst, contentType, metadata)
|
||||
}
|
||||
|
||||
func (s *tracedStore) Delete(ctx context.Context, key string) error {
|
||||
ctx, span := s.start(ctx, "DeleteObject")
|
||||
defer span.End()
|
||||
return s.inner.Delete(ctx, key)
|
||||
}
|
||||
|
||||
func (s *tracedStore) List(ctx context.Context, prefix string) ([]objectstore.Object, error) {
|
||||
ctx, span := s.start(ctx, "ListObjects")
|
||||
defer span.End()
|
||||
return s.inner.List(ctx, prefix)
|
||||
}
|
||||
|
||||
func (s *tracedStore) PresignPut(ctx context.Context, key string, size int64, ttl time.Duration) (string, time.Time, error) {
|
||||
ctx, span := s.start(ctx, "PresignPut")
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.Int64("aws.s3.object.size", size), attribute.String("aws.s3.presign.ttl", ttl.String()))
|
||||
return s.inner.PresignPut(ctx, key, size, ttl)
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
// RegisterProcessMetrics exposes this process/container CPU and memory. It
|
||||
// uses cgroup v2 when available and /proc as a fallback. The metrics are
|
||||
// intentionally process-scoped: no Docker socket or host root is required.
|
||||
func RegisterProcessMetrics() error {
|
||||
initMetrics()
|
||||
_, err := otel.Meter("messenger").RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
||||
cpu, memory, limit := readProcessStats()
|
||||
o.ObserveFloat64(processCPU, cpu)
|
||||
o.ObserveInt64(processMemory, memory)
|
||||
o.ObserveInt64(processMemLimit, limit)
|
||||
return nil
|
||||
}, processCPU, processMemory, processMemLimit)
|
||||
return err
|
||||
}
|
||||
|
||||
func readProcessStats() (cpuSeconds float64, memoryBytes, memoryLimit int64) {
|
||||
if value, ok := readCgroupCPU(); ok {
|
||||
cpuSeconds = value
|
||||
} else {
|
||||
cpuSeconds = readProcCPU()
|
||||
}
|
||||
memoryBytes = readCgroupMemory()
|
||||
if memoryBytes == 0 {
|
||||
memoryBytes = readProcRSS()
|
||||
}
|
||||
memoryLimit = readCgroupMemoryLimit()
|
||||
return cpuSeconds, memoryBytes, memoryLimit
|
||||
}
|
||||
|
||||
func readCgroupCPU() (float64, bool) {
|
||||
raw, err := os.ReadFile("/sys/fs/cgroup/cpu.stat")
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) == 2 && fields[0] == "usage_usec" {
|
||||
usec, err := strconv.ParseFloat(fields[1], 64)
|
||||
if err == nil {
|
||||
return usec / 1e6, true
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func readProcCPU() float64 {
|
||||
raw, err := os.ReadFile("/proc/self/stat")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
// comm may contain spaces; fields after the closing parenthesis are stable.
|
||||
end := strings.LastIndexByte(string(raw), ')')
|
||||
if end < 0 {
|
||||
return 0
|
||||
}
|
||||
fields := strings.Fields(string(raw)[end+1:])
|
||||
if len(fields) < 15 {
|
||||
return 0
|
||||
}
|
||||
utime, _ := strconv.ParseFloat(fields[11], 64)
|
||||
stime, _ := strconv.ParseFloat(fields[12], 64)
|
||||
return (utime + stime) / 100 // USER_HZ on Linux is 100 in the images used.
|
||||
}
|
||||
|
||||
func readCgroupMemory() int64 {
|
||||
for _, path := range []string{"/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory/memory.usage_in_bytes"} {
|
||||
if raw, err := os.ReadFile(path); err == nil {
|
||||
if value, err := strconv.ParseInt(strings.TrimSpace(string(raw)), 10, 64); err == nil {
|
||||
return value
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func readCgroupMemoryLimit() int64 {
|
||||
for _, path := range []string{"/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"} {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
value := strings.TrimSpace(string(raw))
|
||||
if value == "max" {
|
||||
return 0
|
||||
}
|
||||
if parsed, err := strconv.ParseInt(value, 10, 64); err == nil {
|
||||
return parsed
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func readProcRSS() int64 {
|
||||
file, err := os.Open("/proc/self/status")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
fields := strings.Fields(scanner.Text())
|
||||
if len(fields) >= 2 && fields[0] == "VmRSS:" {
|
||||
if kb, err := strconv.ParseInt(fields[1], 10, 64); err == nil {
|
||||
return kb * 1024
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
// Package telemetry wires OpenTelemetry traces, metrics and logs to OTLP and
|
||||
// provides the small set of instruments used by the application. Telemetry is
|
||||
// best-effort: a missing Collector must never fail startup or readiness.
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
"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"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
|
||||
|
||||
"mtusi-messenger/internal/platform/instanceid"
|
||||
)
|
||||
|
||||
// Shutdown flushes and closes providers. It is safe to call once.
|
||||
type Shutdown func(context.Context) error
|
||||
|
||||
var (
|
||||
globalLogProvider *sdklog.LoggerProvider
|
||||
shutdownOnce sync.Once
|
||||
)
|
||||
|
||||
// Enabled reports whether TELEMETRY_ENABLED is not explicitly disabled.
|
||||
func Enabled() bool {
|
||||
return strings.ToLower(strings.TrimSpace(os.Getenv("TELEMETRY_ENABLED"))) != "0"
|
||||
}
|
||||
|
||||
// Setup configures global OTel providers. Exporters are asynchronous and do
|
||||
// not connect synchronously; an unreachable Collector only produces bounded
|
||||
// background export failures.
|
||||
func Setup(ctx context.Context, serviceName, version string) (Shutdown, error) {
|
||||
if !Enabled() {
|
||||
return func(context.Context) error { return nil }, nil
|
||||
}
|
||||
|
||||
// resource.Default carries the SDK's schema URL (currently 1.43.0); using a
|
||||
// different semconv schema in NewWithAttributes conflicts. The code resource
|
||||
// is schemaless, while the SDK still provides telemetry.sdk.* attributes.
|
||||
res, err := resource.Merge(
|
||||
resource.Default(),
|
||||
resource.NewSchemaless(
|
||||
semconv.ServiceName(serviceName),
|
||||
semconv.ServiceVersion(defaultVersion(version)),
|
||||
semconv.ServiceInstanceID(instanceid.FromEnvOrHostname()),
|
||||
semconv.DeploymentEnvironmentName("lab"),
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build telemetry resource: %w", err)
|
||||
}
|
||||
|
||||
traceExporter, err := otlptracehttp.New(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create trace exporter: %w", err)
|
||||
}
|
||||
metricExporter, err := otlpmetrichttp.New(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create metric exporter: %w", err)
|
||||
}
|
||||
logExporter, err := otlploghttp.New(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create log exporter: %w", err)
|
||||
}
|
||||
|
||||
tracerProvider := sdktrace.NewTracerProvider(
|
||||
sdktrace.WithResource(res),
|
||||
sdktrace.WithSampler(samplerFromEnv()),
|
||||
sdktrace.WithBatcher(traceExporter,
|
||||
sdktrace.WithMaxQueueSize(2048),
|
||||
sdktrace.WithMaxExportBatchSize(512),
|
||||
sdktrace.WithBatchTimeout(5*time.Second),
|
||||
sdktrace.WithExportTimeout(5*time.Second),
|
||||
),
|
||||
)
|
||||
|
||||
meterProvider := sdkmetric.NewMeterProvider(
|
||||
sdkmetric.WithResource(res),
|
||||
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(
|
||||
metricExporter,
|
||||
sdkmetric.WithInterval(metricInterval()),
|
||||
sdkmetric.WithTimeout(5*time.Second),
|
||||
)),
|
||||
)
|
||||
|
||||
loggerProvider := sdklog.NewLoggerProvider(
|
||||
sdklog.WithResource(res),
|
||||
sdklog.WithProcessor(sdklog.NewBatchProcessor(
|
||||
logExporter,
|
||||
sdklog.WithExportInterval(5*time.Second),
|
||||
sdklog.WithExportTimeout(5*time.Second),
|
||||
sdklog.WithMaxQueueSize(2048),
|
||||
sdklog.WithExportMaxBatchSize(512),
|
||||
)),
|
||||
)
|
||||
|
||||
otel.SetTracerProvider(tracerProvider)
|
||||
otel.SetMeterProvider(meterProvider)
|
||||
otel.SetLoggerProvider(loggerProvider)
|
||||
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
|
||||
propagation.TraceContext{},
|
||||
propagation.Baggage{},
|
||||
))
|
||||
|
||||
globalLogProvider = loggerProvider
|
||||
initMetrics()
|
||||
|
||||
return func(shutdownCtx context.Context) error {
|
||||
var errs []error
|
||||
shutdownOnce.Do(func() {
|
||||
// Each provider gets its own bounded budget. Sharing one short context
|
||||
// lets a slow trace flush starve the metric/log flush on shutdown.
|
||||
flush := func(fn func(context.Context) error) error {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(shutdownCtx), 2*time.Second)
|
||||
defer cancel()
|
||||
return fn(ctx)
|
||||
}
|
||||
errs = append(errs,
|
||||
flush(tracerProvider.Shutdown),
|
||||
flush(meterProvider.Shutdown),
|
||||
flush(loggerProvider.Shutdown),
|
||||
)
|
||||
})
|
||||
return errors.Join(errs...)
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GlobalLoggerProvider exposes the configured log provider for the slog fanout.
|
||||
func GlobalLoggerProvider() *sdklog.LoggerProvider {
|
||||
return globalLogProvider
|
||||
}
|
||||
|
||||
func defaultVersion(version string) string {
|
||||
if strings.TrimSpace(version) == "" {
|
||||
return "dev"
|
||||
}
|
||||
return version
|
||||
}
|
||||
|
||||
func metricInterval() time.Duration {
|
||||
raw := strings.TrimSpace(os.Getenv("OTEL_METRIC_EXPORT_INTERVAL"))
|
||||
if raw == "" {
|
||||
return 15 * time.Second
|
||||
}
|
||||
ms, err := strconv.Atoi(raw)
|
||||
if err != nil || ms <= 0 {
|
||||
return 15 * time.Second
|
||||
}
|
||||
return time.Duration(ms) * time.Millisecond
|
||||
}
|
||||
|
||||
func samplerFromEnv() sdktrace.Sampler {
|
||||
name := strings.ToLower(strings.TrimSpace(os.Getenv("OTEL_TRACES_SAMPLER")))
|
||||
ratio := 1.0
|
||||
if raw := strings.TrimSpace(os.Getenv("OTEL_TRACES_SAMPLER_ARG")); raw != "" {
|
||||
if parsed, err := strconv.ParseFloat(raw, 64); err == nil {
|
||||
ratio = parsed
|
||||
}
|
||||
}
|
||||
switch name {
|
||||
case "always_off":
|
||||
return sdktrace.NeverSample()
|
||||
case "traceidratio":
|
||||
return sdktrace.TraceIDRatioBased(ratio)
|
||||
case "parentbased_traceidratio":
|
||||
return sdktrace.ParentBased(sdktrace.TraceIDRatioBased(ratio))
|
||||
default:
|
||||
// The lab needs complete traces to prove the upload -> worker chain.
|
||||
return sdktrace.ParentBased(sdktrace.AlwaysSample())
|
||||
}
|
||||
}
|
||||
@@ -81,8 +81,6 @@ func (e *Extensions) route(method, operation string, handler extensionHandler) h
|
||||
slog.String("request_id", requestIDFromContext(r.Context())),
|
||||
slog.String("operation", operation),
|
||||
slog.String("method", r.Method),
|
||||
slog.String("path", r.URL.Path),
|
||||
slog.String("user_id", userID.String()),
|
||||
slog.Int("status", writer.statusCode()),
|
||||
slog.Duration("duration", time.Since(started)),
|
||||
)
|
||||
@@ -205,7 +203,6 @@ func (e *Extensions) fail(w http.ResponseWriter, r *http.Request, err error) {
|
||||
e.log.ErrorContext(r.Context(), "extension request failed",
|
||||
slog.String("request_id", requestIDFromContext(r.Context())),
|
||||
slog.String("method", r.Method),
|
||||
slog.String("path", r.URL.Path),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -75,7 +75,6 @@ func logRejected(ctx context.Context, log *slog.Logger, r *http.Request, status
|
||||
attrs := []any{
|
||||
slog.String("request_id", requestIDFromContext(ctx)),
|
||||
slog.String("method", r.Method),
|
||||
slog.String("path", r.URL.Path),
|
||||
slog.Int("status", status),
|
||||
}
|
||||
|
||||
|
||||
@@ -3,12 +3,15 @@ package rest
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const requestIDHeader = "X-Request-ID"
|
||||
|
||||
var requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
|
||||
|
||||
type requestIDKey struct{}
|
||||
|
||||
func requestIDFromContext(ctx context.Context) string {
|
||||
@@ -24,7 +27,7 @@ func withRequestID(ctx context.Context, id string) context.Context {
|
||||
func requestIDMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get(requestIDHeader)
|
||||
if id == "" {
|
||||
if !requestIDPattern.MatchString(id) {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ func NewRouter(
|
||||
oas.WithErrorHandler(newErrorHandler(log)),
|
||||
oas.WithNotFound(newNotFoundHandler(log)),
|
||||
oas.WithMethodNotAllowed(newMethodNotAllowedHandler(log)),
|
||||
oas.WithMiddleware(loggingMiddleware(log)),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -38,7 +37,9 @@ func NewRouter(
|
||||
|
||||
mux.Handle("/", server)
|
||||
|
||||
limited := bodyLimitMiddleware(maxBodyBytes, maxUploadBytes, log, mux)
|
||||
|
||||
return requestIDMiddleware(
|
||||
instanceIDMiddleware(InstanceID(), bodyLimitMiddleware(maxBodyBytes, maxUploadBytes, log, mux)),
|
||||
instanceIDMiddleware(InstanceID(), telemetryMiddleware(log, server, mux, limited)),
|
||||
), nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi-messenger/internal/telemetry"
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
// telemetryMiddleware is the single source of HTTP spans, metrics and access
|
||||
// logs. It resolves the OpenAPI template before the span is started: the
|
||||
// generated ogen router does not set http.Request.Pattern for its routes.
|
||||
func telemetryMiddleware(log *slog.Logger, server *oas.Server, mux *http.ServeMux, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
route, operation := resolveRoute(server, mux, r)
|
||||
if strings.HasPrefix(route, "/health/") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
||||
method := normalizeMethod(r.Method)
|
||||
started := time.Now()
|
||||
ctx, span := otel.Tracer("messenger/http").Start(ctx, method+" "+route,
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("http.request.method", method),
|
||||
attribute.String("http.route", route),
|
||||
),
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
writer := &statusWriter{ResponseWriter: w}
|
||||
next.ServeHTTP(writer, r.WithContext(ctx))
|
||||
|
||||
status := writer.statusCode()
|
||||
span.SetAttributes(attribute.Int("http.response.status_code", status))
|
||||
if status >= http.StatusInternalServerError {
|
||||
span.SetStatus(codes.Error, http.StatusText(status))
|
||||
}
|
||||
telemetry.RecordHTTP(ctx, method, route, status, time.Since(started))
|
||||
|
||||
attrs := []any{
|
||||
slog.String("event", "http.request.completed"),
|
||||
slog.String("operation", operation),
|
||||
slog.String("route", route),
|
||||
slog.String("method", method),
|
||||
slog.Int("status", status),
|
||||
slog.Duration("duration", time.Since(started)),
|
||||
slog.String("request_id", requestIDFromContext(ctx)),
|
||||
}
|
||||
level := slog.LevelInfo
|
||||
if status >= http.StatusInternalServerError {
|
||||
level = slog.LevelError
|
||||
} else if status >= http.StatusBadRequest {
|
||||
level = slog.LevelWarn
|
||||
}
|
||||
log.Log(ctx, level, "http.request.completed", attrs...)
|
||||
})
|
||||
}
|
||||
|
||||
// normalizeMethod keeps the metric/span label set low-cardinality. Any method
|
||||
// outside the standard set is deliberately collapsed to OTHER.
|
||||
func normalizeMethod(method string) string {
|
||||
switch method {
|
||||
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead, http.MethodOptions:
|
||||
return method
|
||||
default:
|
||||
return "OTHER"
|
||||
}
|
||||
}
|
||||
|
||||
func resolveRoute(server *oas.Server, mux *http.ServeMux, r *http.Request) (route, operation string) {
|
||||
if route, ok := server.FindPath(r.Method, r.URL); ok {
|
||||
return route.PathPattern(), route.OperationID()
|
||||
}
|
||||
if _, pattern := mux.Handler(r); pattern != "" && pattern != "/" {
|
||||
return pattern, ""
|
||||
}
|
||||
return "unmatched", ""
|
||||
}
|
||||
+39
-14
@@ -16,6 +16,7 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -27,6 +28,7 @@ import (
|
||||
"mtusi-messenger/internal/imagecheck"
|
||||
"mtusi-messenger/internal/imageproc"
|
||||
"mtusi-messenger/internal/platform/objectstore"
|
||||
"mtusi-messenger/internal/telemetry"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
@@ -83,6 +85,7 @@ type Worker struct {
|
||||
|
||||
mu sync.RWMutex
|
||||
running bool
|
||||
busy atomic.Int64
|
||||
}
|
||||
|
||||
func New(repo Repository, store Store, config Config, log *slog.Logger) *Worker {
|
||||
@@ -140,6 +143,12 @@ func (w *Worker) setRunning(value bool) {
|
||||
w.running = value
|
||||
}
|
||||
|
||||
// Busy returns the number of worker slots currently processing a job.
|
||||
func (w *Worker) Busy() int64 { return w.busy.Load() }
|
||||
|
||||
// Capacity returns the configured worker concurrency.
|
||||
func (w *Worker) Capacity() int { return w.config.Concurrency }
|
||||
|
||||
func (w *Worker) Ready() (consumerRunning, brokerConnected bool) {
|
||||
w.mu.RLock()
|
||||
running := w.running
|
||||
@@ -160,6 +169,10 @@ func (w *Worker) handle(ctx context.Context, delivery amqp.Delivery) broker.Outc
|
||||
return broker.Drop
|
||||
}
|
||||
|
||||
ctx, span := telemetry.StartConsumerSpan(ctx, message)
|
||||
defer span.End()
|
||||
started := time.Now()
|
||||
|
||||
result, err := w.repo.ClaimJob(ctx, message, w.config.Owner, w.config.LeaseTTL)
|
||||
if err != nil {
|
||||
w.log.WarnContext(ctx, "claim job failed", slog.String("job_id", message.JobID.String()), slog.Any("error", err))
|
||||
@@ -188,14 +201,19 @@ func (w *Worker) handle(ctx context.Context, delivery amqp.Delivery) broker.Outc
|
||||
return broker.Ack
|
||||
}
|
||||
|
||||
return w.process(ctx, result)
|
||||
outcome, label := w.process(ctx, result)
|
||||
telemetry.RecordJobAttempt(ctx, message.Type, label, time.Since(started))
|
||||
|
||||
return outcome
|
||||
}
|
||||
|
||||
func (w *Worker) process(
|
||||
ctx context.Context,
|
||||
result domain.ClaimResult,
|
||||
) broker.Outcome {
|
||||
) (broker.Outcome, string) {
|
||||
job := result.Job
|
||||
w.busy.Add(1)
|
||||
defer w.busy.Add(-1)
|
||||
attachment := result.Attachment
|
||||
|
||||
failpoint.Check("WORKER_AFTER_CLAIM", job.ID)
|
||||
@@ -264,13 +282,18 @@ func (w *Worker) process(
|
||||
slog.String("job_id", job.ID.String()),
|
||||
)
|
||||
|
||||
return broker.Ack
|
||||
return broker.Ack, "superseded"
|
||||
}
|
||||
|
||||
if errors.Is(err, errCompletionCASLost) {
|
||||
return broker.Ack, "superseded"
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
failpoint.Check("WORKER_AFTER_COMMIT", job.ID)
|
||||
telemetry.RecordJobReady(ctx, job.PipelineVersion, time.Since(job.CreatedAt))
|
||||
|
||||
return broker.Ack
|
||||
return broker.Ack, "succeeded"
|
||||
}
|
||||
|
||||
return w.fail(ctx, job, err)
|
||||
@@ -384,7 +407,7 @@ func (w *Worker) runJob(
|
||||
if !completed {
|
||||
w.log.WarnContext(ctx, "completion CAS lost", slog.String("job_id", job.ID.String()))
|
||||
|
||||
return nil
|
||||
return errCompletionCASLost
|
||||
}
|
||||
|
||||
w.log.InfoContext(ctx, "attachment ready",
|
||||
@@ -451,7 +474,7 @@ func (w *Worker) spoolSource(ctx context.Context, key string) (*os.File, int64,
|
||||
return file, size, hex.EncodeToString(hasher.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func (w *Worker) fail(ctx context.Context, job domain.Job, err error) broker.Outcome {
|
||||
func (w *Worker) fail(ctx context.Context, job domain.Job, err error) (broker.Outcome, string) {
|
||||
if ctx.Err() != nil {
|
||||
// Parent cancellation means graceful shutdown. Keep the attempt number:
|
||||
// an operator restart must not consume the processing budget. The job
|
||||
@@ -465,12 +488,12 @@ func (w *Worker) fail(ctx context.Context, job domain.Job, err error) broker.Out
|
||||
time.Now().Add(time.Second), true, "shutdown",
|
||||
)
|
||||
if retryErr != nil {
|
||||
return broker.Requeue
|
||||
return broker.Requeue, "failed"
|
||||
}
|
||||
|
||||
_ = failed
|
||||
|
||||
return broker.Ack
|
||||
return broker.Ack, "shutdown"
|
||||
}
|
||||
|
||||
code := "processing_failed"
|
||||
@@ -504,13 +527,13 @@ func (w *Worker) fail(ctx context.Context, job domain.Job, err error) broker.Out
|
||||
|
||||
ok, failErr := w.repo.FailJob(ctx, job.ID, job.Attempt, w.config.Owner, code)
|
||||
if failErr != nil {
|
||||
return broker.Requeue
|
||||
return broker.Requeue, "failed"
|
||||
}
|
||||
if !ok {
|
||||
return broker.Ack
|
||||
return broker.Ack, "failed"
|
||||
}
|
||||
|
||||
return broker.Drop
|
||||
return broker.Drop, "failed"
|
||||
}
|
||||
|
||||
next := time.Now().Add(w.backoff(job.Attempt))
|
||||
@@ -525,14 +548,14 @@ func (w *Worker) fail(ctx context.Context, job domain.Job, err error) broker.Out
|
||||
ctx, job.ID, job.Attempt, w.config.Owner, code, next, false, "retry",
|
||||
)
|
||||
if retryErr != nil {
|
||||
return broker.Requeue
|
||||
return broker.Requeue, "retried"
|
||||
}
|
||||
|
||||
if failed {
|
||||
return broker.Drop
|
||||
return broker.Drop, "failed"
|
||||
}
|
||||
|
||||
return broker.Ack
|
||||
return broker.Ack, "retried"
|
||||
}
|
||||
|
||||
func (w *Worker) backoff(attempt int) time.Duration {
|
||||
@@ -559,6 +582,8 @@ func (w *Worker) backoff(attempt int) time.Duration {
|
||||
return time.Duration(rand.Int64N(int64(base))) + time.Millisecond
|
||||
}
|
||||
|
||||
var errCompletionCASLost = errors.New("completion CAS lost")
|
||||
|
||||
type permanentError struct {
|
||||
code string
|
||||
err error
|
||||
|
||||
Reference in New Issue
Block a user