forked from mtusi2026/mtusi2026lab6
feat: add OpenTelemetry instrumentation
This commit is contained in:
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user