feat: add OpenTelemetry instrumentation
This commit is contained in:
@@ -1,104 +1,106 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
var workerDurationBuckets = []float64{0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 15, 20, 30, 60}
|
||||
|
||||
type Metrics struct {
|
||||
workerInFlight prometheus.Gauge
|
||||
workerJobs *prometheus.CounterVec
|
||||
workerDuration *prometheus.HistogramVec
|
||||
workerRetries prometheus.Counter
|
||||
workerReclaimed prometheus.Counter
|
||||
outboxPublished prometheus.Counter
|
||||
outboxPublishFailure prometheus.Counter
|
||||
outboxRecovered prometheus.Counter
|
||||
meter metric.Meter
|
||||
workerInFlight metric.Int64UpDownCounter
|
||||
workerJobs metric.Int64Counter
|
||||
workerDuration metric.Float64Histogram
|
||||
workerTimeToReady metric.Float64Histogram
|
||||
workerRetries metric.Int64Counter
|
||||
workerReclaimed metric.Int64Counter
|
||||
outboxPublished metric.Int64Counter
|
||||
outboxPublishFailure metric.Int64Counter
|
||||
outboxRecovered metric.Int64Counter
|
||||
handler http.Handler
|
||||
}
|
||||
|
||||
func NewMetrics() *Metrics {
|
||||
registry := prometheus.NewRegistry()
|
||||
metrics := &Metrics{
|
||||
workerInFlight: prometheus.NewGauge(prometheus.GaugeOpts{
|
||||
Namespace: "messenger", Subsystem: "attachment_worker", Name: "jobs_in_flight",
|
||||
Help: "Attachment jobs currently processed by this worker.",
|
||||
}),
|
||||
workerJobs: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "messenger", Subsystem: "attachment_worker", Name: "jobs_total",
|
||||
Help: "Completed attachment job deliveries by result.",
|
||||
}, []string{"result"}),
|
||||
workerDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Namespace: "messenger", Subsystem: "attachment_worker", Name: "job_duration_seconds",
|
||||
Help: "Attachment job delivery processing duration.", Buckets: workerDurationBuckets,
|
||||
}, []string{"result"}),
|
||||
workerRetries: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: "messenger", Subsystem: "attachment_worker", Name: "retries_total",
|
||||
Help: "Attachment jobs scheduled for another attempt.",
|
||||
}),
|
||||
workerReclaimed: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: "messenger", Subsystem: "attachment_worker", Name: "reclaimed_deliveries_total",
|
||||
Help: "Redis Stream deliveries reclaimed after their idle timeout.",
|
||||
}),
|
||||
outboxPublished: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: "messenger", Subsystem: "outbox", Name: "published_total",
|
||||
Help: "Outbox events confirmed by Redis Streams.",
|
||||
}),
|
||||
outboxPublishFailure: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: "messenger", Subsystem: "outbox", Name: "publish_failures_total",
|
||||
Help: "Outbox events whose Redis Streams publish failed.",
|
||||
}),
|
||||
outboxRecovered: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: "messenger", Subsystem: "outbox", Name: "recovered_leases_total",
|
||||
Help: "Expired outbox leases returned for publication.",
|
||||
}),
|
||||
func NewMetrics(meter metric.Meter, handler http.Handler, workerCapacity int) *Metrics {
|
||||
if meter == nil {
|
||||
meter = otel.Meter("messenger-pipeline")
|
||||
}
|
||||
registry.MustRegister(
|
||||
metrics.workerInFlight, metrics.workerJobs, metrics.workerDuration,
|
||||
metrics.workerRetries, metrics.workerReclaimed, metrics.outboxPublished,
|
||||
metrics.outboxPublishFailure, metrics.outboxRecovered,
|
||||
collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||||
if handler == nil {
|
||||
handler = http.NotFoundHandler()
|
||||
}
|
||||
workerInFlight, _ := meter.Int64UpDownCounter("messenger_attachment_worker_jobs_in_flight", metric.WithDescription("Attachment jobs currently processed by this worker."))
|
||||
workerJobs, _ := meter.Int64Counter("messenger_attachment_worker_jobs", metric.WithDescription("Completed attachment job deliveries by result."))
|
||||
workerDuration, _ := meter.Float64Histogram("messenger_attachment_worker_job_duration",
|
||||
metric.WithDescription("Attachment job delivery processing duration."), metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(workerDurationBuckets...),
|
||||
)
|
||||
metrics.handler = promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
|
||||
return metrics
|
||||
workerTimeToReady, _ := meter.Float64Histogram("messenger_attachment_time_to_ready",
|
||||
metric.WithDescription("Elapsed time from durable job creation to ready state."), metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(workerDurationBuckets...),
|
||||
)
|
||||
workerRetries, _ := meter.Int64Counter("messenger_attachment_worker_retries", metric.WithDescription("Attachment jobs scheduled for another attempt."))
|
||||
workerReclaimed, _ := meter.Int64Counter("messenger_attachment_worker_reclaimed_deliveries", metric.WithDescription("Redis Stream deliveries reclaimed after their idle timeout."))
|
||||
outboxPublished, _ := meter.Int64Counter("messenger_outbox_published", metric.WithDescription("Outbox events confirmed by Redis Streams."))
|
||||
outboxPublishFailure, _ := meter.Int64Counter("messenger_outbox_publish_failures", metric.WithDescription("Outbox events whose Redis Streams publish failed."))
|
||||
outboxRecovered, _ := meter.Int64Counter("messenger_outbox_recovered_leases", metric.WithDescription("Expired outbox leases returned for publication."))
|
||||
if workerCapacity > 0 {
|
||||
_, _ = meter.Int64ObservableGauge("messenger_attachment_worker_capacity",
|
||||
metric.WithDescription("Maximum concurrent attachment jobs for this worker."),
|
||||
metric.WithInt64Callback(func(_ context.Context, observer metric.Int64Observer) error {
|
||||
observer.Observe(int64(workerCapacity))
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
}
|
||||
return &Metrics{
|
||||
meter: meter, workerInFlight: workerInFlight, workerJobs: workerJobs,
|
||||
workerDuration: workerDuration, workerTimeToReady: workerTimeToReady,
|
||||
workerRetries: workerRetries, workerReclaimed: workerReclaimed,
|
||||
outboxPublished: outboxPublished, outboxPublishFailure: outboxPublishFailure,
|
||||
outboxRecovered: outboxRecovered, handler: handler,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Metrics) Handler() http.Handler {
|
||||
return m.handler
|
||||
}
|
||||
|
||||
func (m *Metrics) ObserveStarted() {
|
||||
m.workerInFlight.Inc()
|
||||
func (m *Metrics) ObserveStarted(ctx context.Context) {
|
||||
m.workerInFlight.Add(ctx, 1)
|
||||
}
|
||||
|
||||
func (m *Metrics) ObserveFinished(result string, duration time.Duration) {
|
||||
m.workerInFlight.Dec()
|
||||
m.workerJobs.WithLabelValues(result).Inc()
|
||||
m.workerDuration.WithLabelValues(result).Observe(duration.Seconds())
|
||||
func (m *Metrics) ObserveFinished(ctx context.Context, result string, duration time.Duration) {
|
||||
attributes := metric.WithAttributes(attribute.String("job_type", "attachment.process"), attribute.String("result", result))
|
||||
m.workerInFlight.Add(ctx, -1)
|
||||
m.workerJobs.Add(ctx, 1, attributes)
|
||||
m.workerDuration.Record(ctx, duration.Seconds(), attributes)
|
||||
}
|
||||
|
||||
func (m *Metrics) ObserveRetry() {
|
||||
m.workerRetries.Inc()
|
||||
func (m *Metrics) ObserveTimeToReady(ctx context.Context, duration time.Duration) {
|
||||
m.workerTimeToReady.Record(ctx, duration.Seconds(), metric.WithAttributes(attribute.String("job_type", "attachment.process")))
|
||||
}
|
||||
|
||||
func (m *Metrics) ObserveReclaimed(count int) {
|
||||
m.workerReclaimed.Add(float64(count))
|
||||
func (m *Metrics) ObserveRetry(ctx context.Context) {
|
||||
m.workerRetries.Add(ctx, 1)
|
||||
}
|
||||
|
||||
func (m *Metrics) ObservePublished() {
|
||||
m.outboxPublished.Inc()
|
||||
func (m *Metrics) ObserveReclaimed(ctx context.Context, count int) {
|
||||
m.workerReclaimed.Add(ctx, int64(count))
|
||||
}
|
||||
|
||||
func (m *Metrics) ObservePublishFailure() {
|
||||
m.outboxPublishFailure.Inc()
|
||||
func (m *Metrics) ObservePublished(ctx context.Context) {
|
||||
m.outboxPublished.Add(ctx, 1)
|
||||
}
|
||||
|
||||
func (m *Metrics) ObserveRecovered(count int) {
|
||||
m.outboxRecovered.Add(float64(count))
|
||||
func (m *Metrics) ObservePublishFailure(ctx context.Context) {
|
||||
m.outboxPublishFailure.Add(ctx, 1)
|
||||
}
|
||||
|
||||
func (m *Metrics) ObserveRecovered(ctx context.Context, count int) {
|
||||
m.outboxRecovered.Add(ctx, int64(count))
|
||||
}
|
||||
|
||||
@@ -19,7 +19,8 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
@@ -53,8 +54,7 @@ type Upload struct {
|
||||
ContentType string
|
||||
ContentLength int64
|
||||
Body io.Reader
|
||||
Traceparent string
|
||||
Tracestate string
|
||||
TraceContext telemetry.MessageCarrier
|
||||
}
|
||||
|
||||
type Content struct {
|
||||
@@ -112,27 +112,27 @@ func (s *Service) Upload(ctx context.Context, input Upload) (model.Attachment, e
|
||||
return model.Attachment{}, mapDependencyError(err)
|
||||
}
|
||||
if err := s.objects.Put(ctx, stagingKey, contentType, data); err != nil {
|
||||
s.logger.Error("attachment staging write failed", "attachment_id", pending.ID, "error", err)
|
||||
s.deletePending(pending.ID, stagingKey)
|
||||
s.logger.ErrorContext(ctx, "attachment staging write failed", "attachment_id", pending.ID, "error", err)
|
||||
s.deletePending(ctx, pending.ID, stagingKey)
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
createdAt := time.Now().UTC()
|
||||
queued, err := s.repository.QueueAttachmentWithJobAndOutbox(ctx, pending.ID, stagingKey, model.AttachmentJob{
|
||||
ID: uuid.NewString(), AttachmentID: pending.ID, PipelineVersion: s.config.PipelineVersion,
|
||||
Attempt: 1, Status: model.AttachmentJobQueued, AvailableAt: createdAt, CreatedAt: createdAt,
|
||||
}, input.Traceparent, input.Tracestate)
|
||||
}, input.TraceContext.Traceparent, input.TraceContext.Tracestate)
|
||||
if err != nil {
|
||||
s.logger.Error("attachment queue transaction failed", "attachment_id", pending.ID, "error", err)
|
||||
s.logger.ErrorContext(ctx, "attachment queue transaction failed", "attachment_id", pending.ID, "error", err)
|
||||
return model.Attachment{}, mapDependencyError(err)
|
||||
}
|
||||
return queued, nil
|
||||
}
|
||||
|
||||
func (s *Service) deletePending(attachmentID, stagingKey string) {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), s.config.CleanupTimeout)
|
||||
func (s *Service) deletePending(ctx context.Context, attachmentID, stagingKey string) {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), s.config.CleanupTimeout)
|
||||
defer cancel()
|
||||
if err := s.repository.DeletePendingAttachment(cleanupCtx, attachmentID, stagingKey); err != nil {
|
||||
s.logger.Error("pending attachment cleanup failed", "attachment_id", attachmentID, "error", err)
|
||||
s.logger.ErrorContext(cleanupCtx, "pending attachment cleanup failed", "attachment_id", attachmentID, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
)
|
||||
|
||||
func TestUploadLifecycle(t *testing.T) {
|
||||
|
||||
@@ -18,10 +18,16 @@ import (
|
||||
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/broker/redisstream"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment/transform"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/objectstore"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/broker/redisstream"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
@@ -29,7 +35,7 @@ type Repository interface {
|
||||
ClaimAttachmentJob(context.Context, string, string, int, int, string, time.Duration) (model.AttachmentJobLease, error)
|
||||
RenewAttachmentJobLease(context.Context, model.AttachmentJobLease, time.Duration) (bool, error)
|
||||
CompleteAttachmentJob(context.Context, model.AttachmentJobLease, []model.Variant) (model.JobMutationResult, error)
|
||||
RetryAttachmentJob(context.Context, model.AttachmentJobLease, string, time.Time) (model.JobMutationResult, error)
|
||||
RetryAttachmentJob(context.Context, model.AttachmentJobLease, string, time.Time, string, string) (model.JobMutationResult, error)
|
||||
FailAttachmentJob(context.Context, model.AttachmentJobLease, string) (model.JobMutationResult, error)
|
||||
RecoverExpiredAttachmentJobs(context.Context, int, int, time.Time) (model.RecoveryResult, error)
|
||||
}
|
||||
@@ -50,10 +56,11 @@ type ImageProcessor interface {
|
||||
}
|
||||
|
||||
type Metrics interface {
|
||||
ObserveStarted()
|
||||
ObserveFinished(string, time.Duration)
|
||||
ObserveRetry()
|
||||
ObserveReclaimed(int)
|
||||
ObserveStarted(context.Context)
|
||||
ObserveFinished(context.Context, string, time.Duration)
|
||||
ObserveTimeToReady(context.Context, time.Duration)
|
||||
ObserveRetry(context.Context)
|
||||
ObserveReclaimed(context.Context, int)
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
@@ -166,7 +173,7 @@ func (w *Worker) Run(ctx context.Context) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
w.metrics.ObserveReclaimed(len(deliveries))
|
||||
w.metrics.ObserveReclaimed(ctx, len(deliveries))
|
||||
w.processBatch(ctx, deliveries)
|
||||
reclaimCursor = next
|
||||
if reclaimCursor == "" {
|
||||
@@ -189,25 +196,48 @@ func (w *Worker) processBatch(ctx context.Context, deliveries []redisstream.Deli
|
||||
go func(delivery redisstream.Delivery) {
|
||||
defer group.Done()
|
||||
defer func() { <-limit }()
|
||||
if err := w.ProcessDelivery(ctx, delivery, FaultNone); err != nil && ctx.Err() == nil {
|
||||
w.logger.Error("attachment job delivery failed", "message_id", delivery.ID, "error", err)
|
||||
}
|
||||
_ = w.ProcessDelivery(ctx, delivery, FaultNone)
|
||||
}(delivery)
|
||||
}
|
||||
group.Wait()
|
||||
}
|
||||
|
||||
func (w *Worker) ProcessDelivery(ctx context.Context, delivery redisstream.Delivery, fault FaultPoint) error {
|
||||
func (w *Worker) ProcessDelivery(ctx context.Context, delivery redisstream.Delivery, fault FaultPoint) (resultErr error) {
|
||||
started := w.now()
|
||||
w.metrics.ObserveStarted()
|
||||
result := "transient_error"
|
||||
defer func() { w.metrics.ObserveFinished(result, w.now().Sub(started)) }()
|
||||
|
||||
if delivery.DecodeError != nil {
|
||||
w.metrics.ObserveStarted(ctx)
|
||||
defer func() { w.metrics.ObserveFinished(ctx, result, w.now().Sub(started)) }()
|
||||
result = "invalid_job"
|
||||
return delivery.ToFailed(ctx, redisstream.FailedDelivery{Code: "invalid_job", FailedAt: w.now()})
|
||||
}
|
||||
envelope := delivery.Envelope
|
||||
ctx = telemetry.ExtractMessage(ctx, telemetry.MessageCarrier{
|
||||
Traceparent: envelope.Traceparent, Tracestate: envelope.Tracestate,
|
||||
})
|
||||
ctx, span := otel.Tracer("messenger-worker").Start(ctx, "attachment.process", trace.WithSpanKind(trace.SpanKindConsumer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("messaging.system", "redis"), attribute.String("messaging.destination.name", "attachment-jobs"),
|
||||
attribute.String("messaging.message.id", delivery.ID), attribute.String("job.id", envelope.JobID.String()),
|
||||
attribute.String("attachment.id", envelope.AttachmentID.String()), attribute.Int("job.attempt", envelope.Attempt),
|
||||
attribute.Int("pipeline.version", envelope.PipelineVersion),
|
||||
))
|
||||
w.metrics.ObserveStarted(ctx)
|
||||
defer func() {
|
||||
w.metrics.ObserveFinished(ctx, result, w.now().Sub(started))
|
||||
span.SetAttributes(attribute.String("job.outcome", result))
|
||||
if resultErr != nil {
|
||||
span.RecordError(resultErr)
|
||||
span.SetStatus(codes.Error, result)
|
||||
if ctx.Err() == nil {
|
||||
w.logger.ErrorContext(ctx, "attachment job failed", "event", "attachment_job_failed", "message_id", delivery.ID, "job_id", envelope.JobID.String(), "job_type", envelope.Type, "attempt", envelope.Attempt, "result", result, "error", resultErr)
|
||||
}
|
||||
} else {
|
||||
w.logger.InfoContext(ctx, "attachment job completed", "event", "attachment_job_completed", "message_id", delivery.ID, "job_id", envelope.JobID.String(), "job_type", envelope.Type, "attempt", envelope.Attempt, "result", result)
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
|
||||
lease, err := w.repository.ClaimAttachmentJob(
|
||||
ctx, envelope.JobID.String(), envelope.AttachmentID.String(), envelope.PipelineVersion, envelope.Attempt,
|
||||
w.config.WorkerID, w.config.LeaseDuration,
|
||||
@@ -246,7 +276,7 @@ func (w *Worker) ProcessDelivery(ctx context.Context, delivery redisstream.Deliv
|
||||
}
|
||||
if mutation == model.JobMutationApplied && strings.HasPrefix(lease.Attachment.StagingKey, "staging/") {
|
||||
if err := w.objects.Delete(context.WithoutCancel(ctx), lease.Attachment.StagingKey); err != nil {
|
||||
w.logger.Warn("staging cleanup failed", "attachment_id", lease.Attachment.ID, "error", err)
|
||||
w.logger.WarnContext(ctx, "staging cleanup failed", "attachment_id", lease.Attachment.ID, "error", err)
|
||||
}
|
||||
}
|
||||
if mutation != model.JobMutationApplied && mutation != model.JobMutationAlreadyComplete && mutation != model.JobMutationStale {
|
||||
@@ -260,6 +290,7 @@ func (w *Worker) ProcessDelivery(ctx context.Context, delivery redisstream.Deliv
|
||||
return err
|
||||
}
|
||||
result = "ready"
|
||||
w.metrics.ObserveTimeToReady(ctx, w.now().Sub(envelope.CreatedAt))
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -444,7 +475,10 @@ func (w *Worker) resolveProcessingFailure(
|
||||
return "failed", delivery.ToFailed(ctx, redisstream.FailedDelivery{Code: code, FailedAt: w.now()})
|
||||
}
|
||||
nextAttempt := w.now().Add(w.retryDelay(lease.Job.ID, lease.Job.Attempt))
|
||||
mutation, err := w.repository.RetryAttachmentJob(ctx, lease, code, nextAttempt)
|
||||
traceContext := telemetry.ContextCarrier(ctx)
|
||||
mutation, err := w.repository.RetryAttachmentJob(
|
||||
ctx, lease, code, nextAttempt, traceContext.Traceparent, traceContext.Tracestate,
|
||||
)
|
||||
if err != nil {
|
||||
return "transient_error", fmt.Errorf("retry attachment job: %w", err)
|
||||
}
|
||||
@@ -454,7 +488,7 @@ func (w *Worker) resolveProcessingFailure(
|
||||
if mutation != model.JobMutationApplied {
|
||||
return "transient_error", fmt.Errorf("unexpected retry result %q", mutation)
|
||||
}
|
||||
w.metrics.ObserveRetry()
|
||||
w.metrics.ObserveRetry(ctx)
|
||||
return "retry", delivery.Ack(ctx)
|
||||
}
|
||||
|
||||
@@ -502,7 +536,8 @@ func (w *Worker) retryDelay(jobID string, attempt int) time.Duration {
|
||||
|
||||
type nopMetrics struct{}
|
||||
|
||||
func (nopMetrics) ObserveStarted() {}
|
||||
func (nopMetrics) ObserveFinished(string, time.Duration) {}
|
||||
func (nopMetrics) ObserveRetry() {}
|
||||
func (nopMetrics) ObserveReclaimed(int) {}
|
||||
func (nopMetrics) ObserveStarted(context.Context) {}
|
||||
func (nopMetrics) ObserveFinished(context.Context, string, time.Duration) {}
|
||||
func (nopMetrics) ObserveTimeToReady(context.Context, time.Duration) {}
|
||||
func (nopMetrics) ObserveRetry(context.Context) {}
|
||||
func (nopMetrics) ObserveReclaimed(context.Context, int) {}
|
||||
|
||||
@@ -9,9 +9,9 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment/transform"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/objectstore"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore"
|
||||
)
|
||||
|
||||
func TestConfigRequiresEnoughMemoryForMaximumImage(t *testing.T) {
|
||||
|
||||
@@ -13,16 +13,21 @@ import (
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry"
|
||||
)
|
||||
|
||||
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
started := time.Now()
|
||||
result := "client_error"
|
||||
defer func() {
|
||||
s.metrics.attachmentUploads.WithLabelValues(result).Inc()
|
||||
s.metrics.attachmentDuration.Observe(time.Since(started).Seconds())
|
||||
attributes := metric.WithAttributes(attribute.String("result", result))
|
||||
s.metrics.attachmentUploads.Add(r.Context(), 1, attributes)
|
||||
s.metrics.attachmentDuration.Record(r.Context(), time.Since(started).Seconds(), attributes)
|
||||
}()
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
@@ -47,7 +52,7 @@ func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiEr
|
||||
uploaded, err := s.attachments.Upload(r.Context(), attachment.Upload{
|
||||
ChatID: chatID, OwnerID: user.ID, Filename: filename,
|
||||
ContentType: r.Header.Get("Content-Type"), ContentLength: r.ContentLength, Body: r.Body,
|
||||
Traceparent: traceparent(r.Header.Get("traceparent")), Tracestate: tracestate(r.Header.Get("tracestate")),
|
||||
TraceContext: telemetry.ContextCarrier(r.Context()),
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, model.ErrCapacity) {
|
||||
@@ -59,7 +64,7 @@ func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiEr
|
||||
return attachmentError(err)
|
||||
}
|
||||
result = "success"
|
||||
s.metrics.attachmentBytes.Add(float64(uploaded.SizeBytes))
|
||||
s.metrics.attachmentBytes.Add(r.Context(), uploaded.SizeBytes)
|
||||
writeJSON(w, http.StatusAccepted, uploaded)
|
||||
return nil
|
||||
}
|
||||
@@ -128,7 +133,7 @@ func (s *Server) attachmentContent(w http.ResponseWriter, r *http.Request) *apiE
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": content.Attachment.Filename}))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := io.Copy(w, content.Body); err != nil {
|
||||
s.logger.Warn("attachment download interrupted", "attachment_id", content.Attachment.ID, "error", err)
|
||||
s.logger.WarnContext(r.Context(), "attachment download interrupted", "event", "attachment_download_interrupted", "attachment_id", content.Attachment.ID, "error", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
)
|
||||
|
||||
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
@@ -229,7 +229,7 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
return unavailable()
|
||||
}
|
||||
if replay {
|
||||
s.metrics.replays.Inc()
|
||||
s.metrics.replays.Add(r.Context(), 1)
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
return nil
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
)
|
||||
|
||||
type UserRepository interface {
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -17,80 +18,50 @@ var (
|
||||
)
|
||||
|
||||
type metrics struct {
|
||||
requests *prometheus.CounterVec
|
||||
duration *prometheus.HistogramVec
|
||||
inFlight prometheus.Gauge
|
||||
replays prometheus.Counter
|
||||
attachmentUploads *prometheus.CounterVec
|
||||
attachmentDuration prometheus.Histogram
|
||||
attachmentBytes prometheus.Counter
|
||||
requests metric.Int64Counter
|
||||
duration metric.Float64Histogram
|
||||
inFlight metric.Int64UpDownCounter
|
||||
replays metric.Int64Counter
|
||||
attachmentUploads metric.Int64Counter
|
||||
attachmentDuration metric.Float64Histogram
|
||||
attachmentBytes metric.Int64Counter
|
||||
handler http.Handler
|
||||
}
|
||||
|
||||
func newMetrics() *metrics {
|
||||
registry := prometheus.NewRegistry()
|
||||
result := &metrics{
|
||||
requests: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "requests_total",
|
||||
Help: "Completed HTTP requests.",
|
||||
}, []string{"method", "route", "status_class"}),
|
||||
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "request_duration_seconds",
|
||||
Help: "HTTP request duration in seconds.",
|
||||
Buckets: requestDurationBuckets,
|
||||
}, []string{"method", "route"}),
|
||||
inFlight: prometheus.NewGauge(prometheus.GaugeOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "requests_in_flight",
|
||||
Help: "HTTP requests currently being served.",
|
||||
}),
|
||||
replays: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "idempotency_replays_total",
|
||||
Help: "Message requests served from an idempotency record.",
|
||||
}),
|
||||
attachmentUploads: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Name: "attachment_uploads_total",
|
||||
Help: "Completed attachment uploads by result.",
|
||||
}, []string{"result"}),
|
||||
attachmentDuration: prometheus.NewHistogram(prometheus.HistogramOpts{
|
||||
Namespace: "messenger",
|
||||
Name: "attachment_upload_duration_seconds",
|
||||
Help: "Attachment upload duration in seconds.",
|
||||
Buckets: uploadDurationBuckets,
|
||||
}),
|
||||
attachmentBytes: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Name: "attachment_upload_bytes_total",
|
||||
Help: "Bytes accepted by successful attachment uploads.",
|
||||
}),
|
||||
func newMetrics(meter metric.Meter, handler http.Handler) *metrics {
|
||||
if meter == nil {
|
||||
meter = otel.Meter("messenger-api")
|
||||
}
|
||||
registry.MustRegister(
|
||||
result.requests,
|
||||
result.duration,
|
||||
result.inFlight,
|
||||
result.replays,
|
||||
result.attachmentUploads,
|
||||
result.attachmentDuration,
|
||||
result.attachmentBytes,
|
||||
collectors.NewGoCollector(),
|
||||
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||||
if handler == nil {
|
||||
handler = http.NotFoundHandler()
|
||||
}
|
||||
requests, _ := meter.Int64Counter("messenger_http_requests", metric.WithDescription("Completed HTTP requests."))
|
||||
duration, _ := meter.Float64Histogram("messenger_http_request_duration",
|
||||
metric.WithDescription("HTTP request duration."), metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(requestDurationBuckets...),
|
||||
)
|
||||
result.handler = promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
|
||||
return result
|
||||
inFlight, _ := meter.Int64UpDownCounter("messenger_http_requests_in_flight", metric.WithDescription("HTTP requests currently being served."))
|
||||
replays, _ := meter.Int64Counter("messenger_http_idempotency_replays", metric.WithDescription("Message requests served from an idempotency record."))
|
||||
attachmentUploads, _ := meter.Int64Counter("messenger_attachment_uploads", metric.WithDescription("Completed attachment uploads by result."))
|
||||
attachmentDuration, _ := meter.Float64Histogram("messenger_attachment_upload_duration",
|
||||
metric.WithDescription("Attachment upload duration."), metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(uploadDurationBuckets...),
|
||||
)
|
||||
attachmentBytes, _ := meter.Int64Counter("messenger_attachment_upload_bytes", metric.WithDescription("Bytes accepted by successful attachment uploads."), metric.WithUnit("By"))
|
||||
return &metrics{
|
||||
requests: requests, duration: duration, inFlight: inFlight, replays: replays,
|
||||
attachmentUploads: attachmentUploads, attachmentDuration: attachmentDuration,
|
||||
attachmentBytes: attachmentBytes, handler: handler,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *metrics) observe(r *http.Request, status int, started time.Time) {
|
||||
route := routeTemplate(r.URL.Path)
|
||||
m.requests.WithLabelValues(r.Method, route, strconv.Itoa(status/100)+"xx").Inc()
|
||||
m.duration.WithLabelValues(r.Method, route).Observe(time.Since(started).Seconds())
|
||||
func (m *metrics) observe(ctx context.Context, r *http.Request, status int, started time.Time) {
|
||||
attributes := metric.WithAttributes(
|
||||
attribute.String("method", r.Method), attribute.String("route", routeTemplate(r.URL.Path)),
|
||||
attribute.String("status_class", strconv.Itoa(status/100)+"xx"),
|
||||
)
|
||||
m.requests.Add(ctx, 1, attributes)
|
||||
m.duration.Record(ctx, time.Since(started).Seconds(), attributes)
|
||||
}
|
||||
|
||||
func routeTemplate(path string) string {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
|
||||
@@ -6,6 +6,16 @@ import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.34.0"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry"
|
||||
)
|
||||
|
||||
type Dependencies struct {
|
||||
@@ -17,6 +27,8 @@ type Dependencies struct {
|
||||
Passwords PasswordService
|
||||
Database HealthChecker
|
||||
Objects HealthChecker
|
||||
Meter metric.Meter
|
||||
Metrics http.Handler
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
@@ -67,7 +79,8 @@ func NewServer(
|
||||
attachments: dependencies.Attachments, sessions: dependencies.Sessions,
|
||||
passwords: dependencies.Passwords, database: dependencies.Database, objects: dependencies.Objects,
|
||||
sessionTTL: config.SessionTTL, idempotencyTTL: config.IdempotencyTTL, requestTTL: config.RequestTTL,
|
||||
instanceID: config.InstanceID, logger: logger, swaggerPort: config.SwaggerPort, metrics: newMetrics(),
|
||||
instanceID: config.InstanceID, logger: logger, swaggerPort: config.SwaggerPort,
|
||||
metrics: newMetrics(dependencies.Meter, dependencies.Metrics),
|
||||
}
|
||||
s.ready.Store(true)
|
||||
return s
|
||||
@@ -82,27 +95,39 @@ func (s *Server) Handler() http.Handler {
|
||||
}
|
||||
|
||||
func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
|
||||
requestContext := telemetry.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
||||
tracer := otel.Tracer("messenger-api/http")
|
||||
route := routeTemplate(r.URL.Path)
|
||||
requestContext, span := tracer.Start(requestContext, r.Method+" "+route, trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(semconv.HTTPRequestMethodKey.String(r.Method), semconv.HTTPRoute(route)))
|
||||
defer span.End()
|
||||
r = r.WithContext(requestContext)
|
||||
w.Header().Set("X-Instance-Id", s.instanceID)
|
||||
requestID, err := newID()
|
||||
if err != nil {
|
||||
http.Error(w, "server unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
span.SetAttributes(attribute.String("request.id", requestID))
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
wrapped := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
started := time.Now()
|
||||
s.metrics.inFlight.Inc()
|
||||
s.metrics.inFlight.Add(r.Context(), 1)
|
||||
defer func() {
|
||||
s.metrics.inFlight.Dec()
|
||||
s.metrics.inFlight.Add(r.Context(), -1)
|
||||
if recovered := recover(); recovered != nil {
|
||||
s.logger.Error("request panic", "request_id", requestID, "method", r.Method, "path", r.URL.Path)
|
||||
s.logger.ErrorContext(r.Context(), "request panic", "event", "http_request_panic", "request_id", requestID, "method", r.Method, "route", route)
|
||||
if wrapped.status == http.StatusOK {
|
||||
writeError(wrapped, requestID, internalError())
|
||||
}
|
||||
}
|
||||
s.metrics.observe(r, wrapped.status, started)
|
||||
s.logger.Info("request", "request_id", requestID, "method", r.Method, "path", r.URL.Path, "status", wrapped.status, "duration_ms", time.Since(started).Milliseconds())
|
||||
s.metrics.observe(r.Context(), r, wrapped.status, started)
|
||||
span.SetAttributes(semconv.HTTPResponseStatusCode(wrapped.status))
|
||||
if wrapped.status >= http.StatusInternalServerError {
|
||||
span.SetStatus(codes.Error, http.StatusText(wrapped.status))
|
||||
}
|
||||
s.logger.InfoContext(r.Context(), "request", "event", "http_request_completed", "request_id", requestID, "method", r.Method, "route", route, "status", wrapped.status, "duration_ms", time.Since(started).Milliseconds())
|
||||
}()
|
||||
if s.allowSwaggerOrigin(wrapped, r) && r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
|
||||
wrapped.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
|
||||
|
||||
@@ -14,8 +14,8 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
)
|
||||
|
||||
var errDependency = errors.New("dependency unavailable")
|
||||
|
||||
Reference in New Issue
Block a user