forked from mtusi2026/mtusi2026lab6
Добавить наблюдаемость и проверки отказов для ЛР 6
This commit is contained in:
@@ -10,11 +10,16 @@ import (
|
||||
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/telemetry"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
const JobType = "attachment.process.v1"
|
||||
|
||||
type Job struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
ID string `json:"job_id"`
|
||||
@@ -38,7 +43,9 @@ type Work struct {
|
||||
|
||||
func Enqueue(ctx context.Context, tx pgx.Tx, attachmentID string) error {
|
||||
id := idgen.GenerateUUIDv4()
|
||||
_, err := tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id) VALUES($1,$2)`, id, attachmentID)
|
||||
carrier := telemetry.Inject(ctx)
|
||||
_, err := tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,created_at,traceparent,tracestate)
|
||||
VALUES($1,$2,clock_timestamp(),NULLIF($3,''),NULLIF($4,''))`, id, attachmentID, carrier.Get("traceparent"), carrier.Get("tracestate"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -57,7 +64,7 @@ func (r Repo) Claim(ctx context.Context, j Job) (*Work, error) {
|
||||
lease_token=$3,lease_until=now()+$4::interval,updated_at=now()
|
||||
WHERE id=$1 AND attachment_id=$2 AND pipeline_version=$5 AND status='queued'
|
||||
AND next_attempt_at<=now() AND attempt=$6-1
|
||||
RETURNING attempt`, j.ID, j.AttachmentID, w.Token, r.Lease.String(), j.PipelineVersion, j.Attempt).Scan(&w.Attempt)
|
||||
RETURNING attempt,created_at`, j.ID, j.AttachmentID, w.Token, r.Lease.String(), j.PipelineVersion, j.Attempt).Scan(&w.Attempt, &w.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -76,7 +83,10 @@ func (r Repo) Claim(ctx context.Context, j Job) (*Work, error) {
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (r Repo) Complete(ctx context.Context, w *Work, variants []model.Variant) (bool, error) {
|
||||
func (r Repo) Complete(ctx context.Context, w *Work, variants []model.Variant) (_ bool, err error) {
|
||||
ctx, span := telemetry.Tracer.Start(ctx, "db.job.complete",
|
||||
trace.WithAttributes(attribute.String("db.system.name", "postgresql")))
|
||||
defer func() { telemetry.Finish(span, err) }()
|
||||
tx, err := r.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -247,7 +257,7 @@ func (r Repo) Failed(ctx context.Context) ([]map[string]any, error) {
|
||||
}
|
||||
|
||||
func (j Job) Validate() error {
|
||||
if j.SchemaVersion != 1 || j.Type != "attachment.process.v1" || j.PipelineVersion != 1 || j.Attempt < 1 || !idgen.IsValidUUID(j.ID) || !idgen.IsValidUUID(j.AttachmentID) || j.CreatedAt.IsZero() {
|
||||
if j.SchemaVersion != 1 || j.Type != JobType || j.PipelineVersion != 1 || j.Attempt < 1 || !idgen.IsValidUUID(j.ID) || !idgen.IsValidUUID(j.AttachmentID) || j.CreatedAt.IsZero() {
|
||||
return fmt.Errorf("invalid job envelope")
|
||||
}
|
||||
return nil
|
||||
|
||||
+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) {
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
|
||||
"mtusi2026/internal/telemetry"
|
||||
)
|
||||
|
||||
var (
|
||||
jobAttempts, _ = telemetry.Meter.Int64Counter("messenger.job.attempts")
|
||||
jobDuration, _ = telemetry.Meter.Float64Histogram("messenger.job.processing.duration", metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(.005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10, 20, 30, 60, 120, 300))
|
||||
timeToReady, _ = telemetry.Meter.Float64Histogram("messenger.attachment.time_to_ready", metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(.05, .1, .25, .5, 1, 2, 3, 5, 10, 15, 20, 30, 45, 60, 120, 300))
|
||||
)
|
||||
|
||||
func (r *Runtime) ObserveWorker() error {
|
||||
busy, err := telemetry.Meter.Int64ObservableGauge("messenger.worker.busy")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
capacity, err := telemetry.Meter.Int64ObservableGauge("messenger.worker.capacity")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = telemetry.Meter.RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
||||
o.ObserveInt64(busy, r.busy.Load())
|
||||
o.ObserveInt64(capacity, int64(r.Concurrency))
|
||||
return nil
|
||||
}, busy, capacity)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Runtime) ObserveQueue() error {
|
||||
depth, err := telemetry.Meter.Int64ObservableGauge("messenger.queue.depth")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
oldest, err := telemetry.Meter.Float64ObservableGauge("messenger.queue.oldest.age", metric.WithUnit("s"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
lockWaiters, err := telemetry.Meter.Int64ObservableGauge("messenger.db.messages.lock.waiters")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attrs := metric.WithAttributes(attribute.String("queue", Stream))
|
||||
_, err = telemetry.Meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 750*time.Millisecond)
|
||||
defer cancel()
|
||||
var size, waiters int64
|
||||
var age float64
|
||||
err := r.Repo.Pool.QueryRow(ctx, `
|
||||
SELECT count(*), COALESCE(EXTRACT(EPOCH FROM (now() - min(created_at))), 0)::double precision,
|
||||
(SELECT count(*) FROM pg_catalog.pg_locks WHERE relation = 'messages'::regclass AND NOT granted)
|
||||
FROM attachment_jobs WHERE status = 'queued'`).Scan(&size, &age, &waiters)
|
||||
if err == nil {
|
||||
o.ObserveInt64(depth, size, attrs)
|
||||
o.ObserveFloat64(oldest, max(0, age), attrs)
|
||||
o.ObserveInt64(lockWaiters, waiters)
|
||||
}
|
||||
return nil
|
||||
}, depth, oldest, lockWaiters)
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user