forked from mtusi2026/mtusi2026lab6
Добавить наблюдаемость и проверки отказов для ЛР 6
This commit is contained in:
+78
-27
@@ -13,14 +13,21 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/blobstore"
|
||||
"mtusi2026/internal/images"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/telemetry"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
otellog "go.opentelemetry.io/otel/log"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
const Stream = "attachment-jobs-v1"
|
||||
@@ -34,20 +41,24 @@ type Runtime struct {
|
||||
Concurrency int
|
||||
Fault string
|
||||
Retention time.Duration
|
||||
busy atomic.Int64
|
||||
}
|
||||
|
||||
func (r *Runtime) PublishOne(ctx context.Context) (bool, error) {
|
||||
func (r *Runtime) PublishOne(ctx context.Context) (_ bool, err error) {
|
||||
tx, err := r.Repo.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var oid int64
|
||||
j := Job{SchemaVersion: 1, Type: "attachment.process.v1"}
|
||||
err = tx.QueryRow(ctx, `SELECT o.id,j.id,j.attachment_id,j.pipeline_version,o.attempt,j.created_at
|
||||
var parent, state string
|
||||
j := Job{SchemaVersion: 1, Type: JobType}
|
||||
err = tx.QueryRow(ctx, `SELECT o.id,j.id,j.attachment_id,j.pipeline_version,o.attempt,j.created_at,
|
||||
COALESCE(j.traceparent,''),COALESCE(j.tracestate,'')
|
||||
FROM attachment_outbox o JOIN attachment_jobs j ON j.id=o.job_id
|
||||
WHERE o.published_at IS NULL AND o.available_at<=now()
|
||||
ORDER BY o.id LIMIT 1 FOR UPDATE OF o SKIP LOCKED`).Scan(&oid, &j.ID, &j.AttachmentID, &j.PipelineVersion, &j.Attempt, &j.CreatedAt)
|
||||
ORDER BY o.id LIMIT 1 FOR UPDATE OF o SKIP LOCKED`).
|
||||
Scan(&oid, &j.ID, &j.AttachmentID, &j.PipelineVersion, &j.Attempt, &j.CreatedAt, &parent, &state)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
@@ -62,12 +73,21 @@ func (r *Runtime) PublishOne(ctx context.Context) (bool, error) {
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
ctx = telemetry.Extract(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state})
|
||||
ctx, span := telemetry.Tracer.Start(ctx, "attachment.publish", trace.WithSpanKind(trace.SpanKindProducer), messagingAttributes("send", j))
|
||||
defer func() { telemetry.Finish(span, err) }()
|
||||
values := map[string]any{"payload": string(payload)}
|
||||
for key, value := range telemetry.Inject(ctx) {
|
||||
values[key] = value
|
||||
}
|
||||
pubCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
_, err = r.Broker.XAdd(pubCtx, &redis.XAddArgs{Stream: Stream, Values: map[string]any{"payload": string(payload)}}).Result()
|
||||
_, err = r.Broker.XAdd(pubCtx, &redis.XAddArgs{Stream: Stream, Values: values}).Result()
|
||||
cancel()
|
||||
if err != nil {
|
||||
telemetry.Warn(ctx, "attachment.publish_failed", otellog.Int("job.attempt", j.Attempt))
|
||||
return false, err
|
||||
}
|
||||
telemetry.Info(ctx, "attachment.published", otellog.Int("job.attempt", j.Attempt))
|
||||
if r.Fault == "after_publish" {
|
||||
log.Print("FAULT after_publish: duplicate publication expected")
|
||||
os.Exit(86)
|
||||
@@ -79,6 +99,16 @@ func (r *Runtime) PublishOne(ctx context.Context) (bool, error) {
|
||||
return true, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func messagingAttributes(operation string, j Job) trace.SpanStartOption {
|
||||
return trace.WithAttributes(
|
||||
attribute.String("messaging.system", "redis"),
|
||||
attribute.String("messaging.destination.name", Stream),
|
||||
attribute.String("messaging.operation.type", operation),
|
||||
attribute.String("job.type", j.Type),
|
||||
attribute.Int("job.attempt", j.Attempt),
|
||||
)
|
||||
}
|
||||
|
||||
func (r *Runtime) Relay(ctx context.Context) {
|
||||
tick := time.NewTicker(300 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
@@ -163,28 +193,52 @@ func (r *Runtime) deliver(ctx context.Context, m redis.XMessage) {
|
||||
}
|
||||
return
|
||||
}
|
||||
parent, _ := m.Values["traceparent"].(string)
|
||||
state, _ := m.Values["tracestate"].(string)
|
||||
ctx = telemetry.Extract(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state})
|
||||
ctx, span := telemetry.Tracer.Start(ctx, "attachment.consume", trace.WithSpanKind(trace.SpanKindConsumer), messagingAttributes("process", j))
|
||||
defer span.End()
|
||||
w, err := r.Repo.Claim(ctx, j)
|
||||
if err != nil {
|
||||
log.Printf("claim job=%s: %v", j.ID, err)
|
||||
telemetry.SetError(span, "claim_failed")
|
||||
telemetry.Error(ctx, "attachment.claim_failed", otellog.Int("job.attempt", j.Attempt))
|
||||
return
|
||||
}
|
||||
if w != nil {
|
||||
err = r.process(ctx, w)
|
||||
started := time.Now()
|
||||
r.busy.Add(1)
|
||||
code, err := r.process(ctx, w)
|
||||
r.busy.Add(-1)
|
||||
outcome := "success"
|
||||
logFields := []otellog.KeyValue{otellog.String("job.type", j.Type), otellog.Int("job.attempt", j.Attempt)}
|
||||
if code != "" {
|
||||
outcome = "error"
|
||||
telemetry.SetError(span, code)
|
||||
telemetry.Error(ctx, "attachment.attempt_failed", append(logFields, otellog.String("error.type", code))...)
|
||||
} else {
|
||||
telemetry.Info(ctx, "attachment.ready", logFields...)
|
||||
}
|
||||
span.SetAttributes(attribute.String("job.outcome", outcome))
|
||||
attrs := metric.WithAttributes(attribute.String("job_type", j.Type), attribute.String("outcome", outcome))
|
||||
jobAttempts.Add(ctx, 1, attrs)
|
||||
jobDuration.Record(ctx, time.Since(started).Seconds(), attrs)
|
||||
if err != nil {
|
||||
log.Printf("process job=%s attempt=%d: %v", j.ID, w.Attempt, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
span.SetAttributes(attribute.String("job.outcome", "duplicate"))
|
||||
}
|
||||
if r.Fault == "before_ack" {
|
||||
log.Print("FAULT before_ack: durable DB result, pending broker delivery")
|
||||
os.Exit(86)
|
||||
}
|
||||
if err = r.Broker.XAck(ctx, Stream, Group, m.ID).Err(); err != nil {
|
||||
log.Printf("ack job=%s: %v", j.ID, err)
|
||||
telemetry.SetError(span, "ack_failed")
|
||||
telemetry.Warn(ctx, "attachment.ack_failed", otellog.Int("job.attempt", j.Attempt))
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Runtime) process(ctx context.Context, w *Work) error {
|
||||
func (r *Runtime) process(ctx context.Context, w *Work) (string, error) {
|
||||
workCtx, cancel := context.WithTimeout(ctx, r.Timeout)
|
||||
defer cancel()
|
||||
variants, err := r.effects(workCtx, w)
|
||||
@@ -202,30 +256,27 @@ func (r *Runtime) process(ctx context.Context, w *Work) error {
|
||||
case errors.Is(err, blobstore.ErrNotFound):
|
||||
code, permanent = "staging_missing", true
|
||||
}
|
||||
log.Printf("job=%s attempt=%d error_code=%s", w.ID, w.Attempt, code)
|
||||
return r.Repo.Fail(dbCtx, w, code, permanent)
|
||||
return code, r.Repo.Fail(dbCtx, w, code, permanent)
|
||||
}
|
||||
ok, err := r.Repo.Complete(dbCtx, w, variants)
|
||||
if err != nil {
|
||||
return err
|
||||
return "complete_failed", err
|
||||
}
|
||||
if !ok {
|
||||
return errors.New("completion lease expired or replaced; delivery left pending")
|
||||
return "lease_lost", errors.New("completion lease expired or replaced; delivery left pending")
|
||||
}
|
||||
if ok {
|
||||
log.Printf("job=%s attempt=%d ready variants=%d", w.ID, w.Attempt, len(variants))
|
||||
if r.Fault == "after_commit" {
|
||||
log.Print("FAULT after_commit")
|
||||
os.Exit(86)
|
||||
}
|
||||
if err = r.Blobs.Delete(dbCtx, w.StagingKey); err == nil {
|
||||
_, err = r.Repo.Pool.Exec(dbCtx, `UPDATE attachments SET staging_key=NULL WHERE id=$1 AND status='ready'`, w.AttachmentID)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("defer staging cleanup job=%s", w.ID)
|
||||
}
|
||||
timeToReady.Record(ctx, max(0, time.Since(w.CreatedAt).Seconds()), metric.WithAttributes(attribute.String("job_type", w.Type)))
|
||||
if r.Fault == "after_commit" {
|
||||
log.Print("FAULT after_commit")
|
||||
os.Exit(86)
|
||||
}
|
||||
return nil
|
||||
if err = r.Blobs.Delete(dbCtx, w.StagingKey); err == nil {
|
||||
_, err = r.Repo.Pool.Exec(dbCtx, `UPDATE attachments SET staging_key=NULL WHERE id=$1 AND status='ready'`, w.AttachmentID)
|
||||
}
|
||||
if err != nil {
|
||||
telemetry.Warn(ctx, "attachment.staging.cleanup_deferred")
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (r *Runtime) effects(ctx context.Context, w *Work) ([]model.Variant, error) {
|
||||
|
||||
Reference in New Issue
Block a user