forked from mtusi2026/mtusi2026lab6
lab6
This commit is contained in:
@@ -14,6 +14,10 @@ import (
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/smithy-go"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi2026/internal/telemetry"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("object not found")
|
||||
@@ -57,8 +61,10 @@ func NewS3(ctx context.Context, c S3Config) (*S3, error) {
|
||||
return &S3{client: client, bucket: c.Bucket}, nil
|
||||
}
|
||||
|
||||
func (s *S3) Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string) error {
|
||||
_, err := s.client.PutObject(ctx, &s3.PutObjectInput{
|
||||
func (s *S3) Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string) (err error) {
|
||||
ctx, span := startS3(ctx, "s3.put_object", key)
|
||||
defer func() { telemetry.Finish(span, err) }()
|
||||
_, err = s.client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
Body: body,
|
||||
@@ -68,7 +74,9 @@ func (s *S3) Put(ctx context.Context, key string, body io.ReadSeeker, size int64
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
func (s *S3) Get(ctx context.Context, key string) (_ io.ReadCloser, err error) {
|
||||
ctx, span := startS3(ctx, "s3.get_object", key)
|
||||
defer func() { telemetry.Finish(span, err) }()
|
||||
out, err := s.client.GetObject(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
@@ -82,14 +90,28 @@ func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
return out.Body, nil
|
||||
}
|
||||
|
||||
func (s *S3) Delete(ctx context.Context, key string) error {
|
||||
_, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
func (s *S3) Delete(ctx context.Context, key string) (err error) {
|
||||
ctx, span := startS3(ctx, "s3.delete_object", key)
|
||||
defer func() { telemetry.Finish(span, err) }()
|
||||
_, err = s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func startS3(ctx context.Context, operation, key string) (context.Context, trace.Span) {
|
||||
role := "original"
|
||||
switch {
|
||||
case strings.HasPrefix(key, "staging/"):
|
||||
role = "staging"
|
||||
case strings.Contains(key, "/v1/"):
|
||||
role = "variant"
|
||||
}
|
||||
return telemetry.Tracer.Start(ctx, operation, trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(attribute.String("rpc.system", "aws-api"), attribute.String("s3.object.role", role)))
|
||||
}
|
||||
|
||||
func (s *S3) Ping(ctx context.Context) error {
|
||||
body := []byte("ok")
|
||||
if _, err := s.client.PutObject(ctx, &s3.PutObjectInput{
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ func Connect(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
|
||||
|
||||
connCtx, cancel := context.WithTimeout(ctx, cfg.ConnTimeout)
|
||||
defer cancel()
|
||||
pool, err := pgxpool.NewWithConfig(connCtx, poolCfg)
|
||||
pool, err := NewPool(connCtx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi2026/internal/telemetry"
|
||||
)
|
||||
|
||||
type postgresTracer struct{ waiting atomic.Int64 }
|
||||
|
||||
func NewPool(ctx context.Context, cfg *pgxpool.Config) (*pgxpool.Pool, error) {
|
||||
tracer := &postgresTracer{}
|
||||
cfg.ConnConfig.Tracer = tracer
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = tracer.observe(pool)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func (t *postgresTracer) observe(pool *pgxpool.Pool) error {
|
||||
used, err := telemetry.Meter.Int64ObservableGauge("messenger.db.pool.used")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
waiting, err := telemetry.Meter.Int64ObservableGauge("messenger.db.pool.waiting")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
capacity, err := telemetry.Meter.Int64ObservableGauge("messenger.db.pool.capacity")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = telemetry.Meter.RegisterCallback(func(_ context.Context, observer metric.Observer) error {
|
||||
stats := pool.Stat()
|
||||
observer.ObserveInt64(used, int64(stats.AcquiredConns()))
|
||||
observer.ObserveInt64(waiting, t.waiting.Load())
|
||||
observer.ObserveInt64(capacity, int64(stats.MaxConns()))
|
||||
return nil
|
||||
}, used, waiting, capacity)
|
||||
return err
|
||||
}
|
||||
|
||||
func (t *postgresTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
|
||||
if !trace.SpanFromContext(ctx).IsRecording() {
|
||||
return ctx
|
||||
}
|
||||
|
||||
sql := strings.TrimSpace(data.SQL)
|
||||
first := strings.IndexAny(sql, " \t\r\n;")
|
||||
if first >= 0 {
|
||||
sql = sql[:first]
|
||||
}
|
||||
operation := strings.ToUpper(sql)
|
||||
switch operation {
|
||||
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK":
|
||||
default:
|
||||
operation = "OTHER"
|
||||
}
|
||||
ctx, _ = telemetry.Tracer.Start(ctx, "db.query", trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(attribute.String("db.system.name", "postgresql"), attribute.String("db.operation.name", operation)))
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (t *postgresTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
|
||||
if span := trace.SpanFromContext(ctx); span.IsRecording() {
|
||||
err := data.Err
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
err = nil
|
||||
}
|
||||
telemetry.Finish(span, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *postgresTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
|
||||
t.waiting.Add(1)
|
||||
if !trace.SpanFromContext(ctx).IsRecording() {
|
||||
return ctx
|
||||
}
|
||||
ctx, _ = telemetry.Tracer.Start(ctx, "db.pool.acquire", trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(attribute.String("db.system.name", "postgresql")))
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (t *postgresTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, data pgxpool.TraceAcquireEndData) {
|
||||
t.waiting.Add(-1)
|
||||
if span := trace.SpanFromContext(ctx); span.IsRecording() {
|
||||
telemetry.Finish(span, data.Err)
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -25,6 +24,7 @@ import (
|
||||
"mtusi2026/internal/jobs"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/store"
|
||||
"mtusi2026/internal/telemetry"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -162,7 +162,7 @@ func (a *api) handleUploadAttachment(w http.ResponseWriter, r *http.Request, u m
|
||||
err = a.blobs.Put(putCtx, stagingKey, io.NewSectionReader(tmp, 0, n), n, mt)
|
||||
cancel()
|
||||
if err != nil {
|
||||
log.Printf("s3 put failed: %v", err)
|
||||
telemetry.Error(r.Context(), "attachment.staging.write_failed")
|
||||
delCtx, delCancel := context.WithTimeout(baseCtx, 5*time.Second)
|
||||
_ = a.blobs.Delete(delCtx, stagingKey)
|
||||
delCancel()
|
||||
@@ -177,7 +177,7 @@ func (a *api) handleUploadAttachment(w http.ResponseWriter, r *http.Request, u m
|
||||
SizeBytes: n, SHA256: hex.EncodeToString(h.Sum(nil)), ObjectKey: key, StagingKey: stagingKey,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("attachment metadata commit uncertain, staging retained: %v", err)
|
||||
telemetry.Error(r.Context(), "attachment.accept_failed")
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
@@ -252,10 +252,10 @@ func (a *api) handleDownloadAttachment(w http.ResponseWriter, r *http.Request, u
|
||||
t.Stop()
|
||||
if err != nil {
|
||||
if errors.Is(err, blobstore.ErrNotFound) {
|
||||
log.Printf("INCONSISTENCY: metadata without object id=%s key=%s", att.ID, att.ObjectKey)
|
||||
telemetry.Error(r.Context(), "attachment.object_missing")
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
} else {
|
||||
log.Printf("s3 get failed: %v", err)
|
||||
telemetry.Error(r.Context(), "attachment.object_read_failed")
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
||||
}
|
||||
return
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/model"
|
||||
@@ -46,7 +48,9 @@ func (a *api) handleCreateMessage(w http.ResponseWriter, r *http.Request, u mode
|
||||
return
|
||||
}
|
||||
|
||||
m, err := a.store.CreateMessage(r.Context(), chatID, u.ID, key, req.Text, ids)
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Second)
|
||||
defer cancel()
|
||||
m, err := a.store.CreateMessage(ctx, chatID, u.ID, key, req.Text, ids)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrChatNotFound), errors.Is(err, store.ErrAttachmentNotFound):
|
||||
|
||||
@@ -1,30 +1,66 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/felixge/httpsnoop"
|
||||
"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"
|
||||
|
||||
"mtusi2026/internal/store"
|
||||
"mtusi2026/internal/telemetry"
|
||||
)
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
var (
|
||||
httpRequests, _ = telemetry.Meter.Int64Counter("messenger.http.requests")
|
||||
httpDuration, _ = telemetry.Meter.Float64Histogram("messenger.http.request.duration",
|
||||
metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(.001, .0025, .005, .01, .025, .05, .1, .25, .5, 1, 2, 4, 8, 15, 30, 60))
|
||||
)
|
||||
|
||||
func (r *statusRecorder) WriteHeader(status int) {
|
||||
r.status = status
|
||||
r.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func loggingMiddleware(next http.Handler) http.Handler {
|
||||
func observeRequests(root, apiMux *http.ServeMux) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(rec, r)
|
||||
log.Printf("method=%s path=%s status=%d duration=%s",
|
||||
r.Method, r.URL.Path, rec.status, time.Since(start))
|
||||
_, pattern := root.Handler(r)
|
||||
if pattern == "GET /health/live" || pattern == "GET /health/ready" {
|
||||
root.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
_, pattern = apiMux.Handler(r)
|
||||
registeredMethod, route, matched := strings.Cut(pattern, " ")
|
||||
if !matched || (registeredMethod != r.Method && !(r.Method == http.MethodHead && registeredMethod == http.MethodGet)) {
|
||||
route = "<unmatched>"
|
||||
}
|
||||
method := r.Method
|
||||
switch method {
|
||||
case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch,
|
||||
http.MethodDelete, http.MethodConnect, http.MethodOptions, http.MethodTrace:
|
||||
default:
|
||||
method = "_OTHER"
|
||||
}
|
||||
ctx := telemetry.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
||||
ctx, span := telemetry.Tracer.Start(ctx, method+" "+route, trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(attribute.String("http.request.method", method), attribute.String("http.route", route)))
|
||||
defer span.End()
|
||||
result := httpsnoop.CaptureMetrics(root, w, r.WithContext(ctx))
|
||||
statusClass := strconv.Itoa(result.Code/100) + "xx"
|
||||
attrs := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route),
|
||||
attribute.String("status_class", statusClass))
|
||||
httpRequests.Add(ctx, 1, attrs)
|
||||
httpDuration.Record(ctx, result.Duration.Seconds(), attrs)
|
||||
span.SetAttributes(attribute.Int("http.response.status_code", result.Code))
|
||||
severity := otellog.SeverityInfo
|
||||
if result.Code >= 500 {
|
||||
severity = otellog.SeverityError
|
||||
telemetry.SetError(span, statusClass)
|
||||
}
|
||||
telemetry.Event(ctx, severity, "http.request",
|
||||
otellog.String("method", method), otellog.String("route", route), otellog.Int("http.status_code", result.Code),
|
||||
otellog.Float64("duration_s", result.Duration.Seconds()), otellog.String("request_id", w.Header().Get("X-Request-Id")))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -82,10 +82,7 @@ func NewRouterWithCache(
|
||||
root.HandleFunc("GET /health/ready", handleHealthReady(pool, o.Redis, o.Blobs, o.Draining))
|
||||
root.Handle("/", concurrencyMiddleware(s.Limiter, apiMux))
|
||||
|
||||
var h http.Handler = root
|
||||
h = loggingMiddleware(h)
|
||||
h = instanceMiddleware(o.InstanceID, h)
|
||||
return h
|
||||
return instanceMiddleware(o.InstanceID, observeRequests(root, apiMux))
|
||||
}
|
||||
|
||||
func instanceMiddleware(id string, next http.Handler) http.Handler {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -15,11 +15,14 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi2026/internal/cursor"
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/jobs"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/telemetry"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -55,7 +58,10 @@ func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool,
|
||||
return ok, err
|
||||
}
|
||||
|
||||
func (s *Store) CreateAttachment(ctx context.Context, a model.Attachment) (model.Attachment, error) {
|
||||
func (s *Store) CreateAttachment(ctx context.Context, a model.Attachment) (_ model.Attachment, err error) {
|
||||
ctx, span := telemetry.Tracer.Start(ctx, "db.attachment.accept",
|
||||
trace.WithAttributes(attribute.String("db.system.name", "postgresql")))
|
||||
defer func() { telemetry.Finish(span, err) }()
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return a, err
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
func observeProcess() error {
|
||||
_, err := Meter.Float64ObservableCounter("messenger.process.cpu.time",
|
||||
metric.WithUnit("s"),
|
||||
metric.WithFloat64Callback(func(_ context.Context, observer metric.Float64Observer) error {
|
||||
var usage syscall.Rusage
|
||||
if syscall.Getrusage(syscall.RUSAGE_SELF, &usage) == nil {
|
||||
observer.Observe(time.Duration(usage.Utime.Nano() + usage.Stime.Nano()).Seconds())
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = Meter.Int64ObservableGauge("messenger.process.memory.rss",
|
||||
metric.WithUnit("By"),
|
||||
metric.WithInt64Callback(func(_ context.Context, observer metric.Int64Observer) error {
|
||||
raw, err := os.ReadFile("/proc/self/statm")
|
||||
if err == nil {
|
||||
fields := strings.Fields(string(raw))
|
||||
if len(fields) > 1 {
|
||||
if pages, err := strconv.ParseInt(fields[1], 10, 64); err == nil {
|
||||
observer.Observe(pages * int64(os.Getpagesize()))
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
otellog "go.opentelemetry.io/otel/log"
|
||||
logglobal "go.opentelemetry.io/otel/log/global"
|
||||
"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"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi2026/internal/config"
|
||||
)
|
||||
|
||||
const scope = "mtusi2026/messenger"
|
||||
const exportTimeout = time.Second
|
||||
|
||||
var (
|
||||
Tracer = otel.Tracer(scope)
|
||||
Meter = otel.Meter(scope)
|
||||
logger = logglobal.Logger(scope)
|
||||
)
|
||||
|
||||
func Start(ctx context.Context, service, instance string) (func(), error) {
|
||||
if os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") == "" {
|
||||
return func() {}, nil
|
||||
}
|
||||
res, err := resource.New(ctx, resource.WithFromEnv(), resource.WithAttributes(
|
||||
attribute.String("service.name", config.GetEnv("OTEL_SERVICE_NAME", service)),
|
||||
attribute.String("service.version", config.GetEnv("APP_VERSION", "dev")),
|
||||
attribute.String("service.instance.id", instance),
|
||||
))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
traces, err := otlptracehttp.New(ctx,
|
||||
otlptracehttp.WithTimeout(exportTimeout),
|
||||
otlptracehttp.WithRetry(otlptracehttp.RetryConfig{Enabled: false}),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metrics, err := otlpmetrichttp.New(ctx,
|
||||
otlpmetrichttp.WithTimeout(exportTimeout),
|
||||
otlpmetrichttp.WithRetry(otlpmetrichttp.RetryConfig{Enabled: false}),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logs, err := otlploghttp.New(ctx,
|
||||
otlploghttp.WithTimeout(exportTimeout),
|
||||
otlploghttp.WithRetry(otlploghttp.RetryConfig{Enabled: false}),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res),
|
||||
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())),
|
||||
sdktrace.WithBatcher(traces,
|
||||
sdktrace.WithMaxQueueSize(1024), sdktrace.WithMaxExportBatchSize(128),
|
||||
sdktrace.WithBatchTimeout(time.Second), sdktrace.WithExportTimeout(exportTimeout),
|
||||
),
|
||||
)
|
||||
mp := sdkmetric.NewMeterProvider(sdkmetric.WithResource(res),
|
||||
sdkmetric.WithCardinalityLimit(500),
|
||||
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metrics,
|
||||
sdkmetric.WithInterval(2*time.Second), sdkmetric.WithTimeout(2*time.Second),
|
||||
)),
|
||||
)
|
||||
lp := sdklog.NewLoggerProvider(sdklog.WithResource(res),
|
||||
sdklog.WithProcessor(sdklog.NewBatchProcessor(logs,
|
||||
sdklog.WithMaxQueueSize(1024), sdklog.WithExportMaxBatchSize(128),
|
||||
sdklog.WithExportInterval(time.Second), sdklog.WithExportTimeout(exportTimeout),
|
||||
)),
|
||||
)
|
||||
otel.SetTracerProvider(tp)
|
||||
otel.SetMeterProvider(mp)
|
||||
logglobal.SetLoggerProvider(lp)
|
||||
if err := observeProcess(); err != nil {
|
||||
log.Print("telemetry: process metrics unavailable")
|
||||
}
|
||||
return func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := errors.Join(tp.Shutdown(ctx), lp.Shutdown(ctx), mp.Shutdown(ctx)); err != nil {
|
||||
log.Print("telemetry: shutdown did not flush all signals")
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
func Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {
|
||||
return (propagation.TraceContext{}).Extract(ctx, carrier)
|
||||
}
|
||||
|
||||
func Inject(ctx context.Context) propagation.MapCarrier {
|
||||
carrier := make(propagation.MapCarrier, 2)
|
||||
(propagation.TraceContext{}).Inject(ctx, carrier)
|
||||
return carrier
|
||||
}
|
||||
|
||||
func Finish(span trace.Span, err error) {
|
||||
if err != nil {
|
||||
code := "operation_failed"
|
||||
switch {
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
code = "deadline_exceeded"
|
||||
case errors.Is(err, context.Canceled):
|
||||
code = "canceled"
|
||||
}
|
||||
SetError(span, code)
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
|
||||
func SetError(span trace.Span, code string) {
|
||||
span.SetAttributes(attribute.String("error.type", code))
|
||||
span.SetStatus(codes.Error, code)
|
||||
}
|
||||
|
||||
func Event(ctx context.Context, severity otellog.Severity, event string, attrs ...otellog.KeyValue) {
|
||||
var record otellog.Record
|
||||
record.SetTimestamp(time.Now())
|
||||
record.SetSeverity(severity)
|
||||
record.SetSeverityText(severity.String())
|
||||
record.SetBody(otellog.StringValue(event))
|
||||
record.AddAttributes(otellog.String("event", event))
|
||||
record.AddAttributes(attrs...)
|
||||
logger.Emit(ctx, record)
|
||||
}
|
||||
|
||||
func Warn(ctx context.Context, event string, attrs ...otellog.KeyValue) {
|
||||
Event(ctx, otellog.SeverityWarn, event, attrs...)
|
||||
}
|
||||
|
||||
func Error(ctx context.Context, event string, attrs ...otellog.KeyValue) {
|
||||
Event(ctx, otellog.SeverityError, event, attrs...)
|
||||
}
|
||||
|
||||
func Info(ctx context.Context, event string, attrs ...otellog.KeyValue) {
|
||||
Event(ctx, otellog.SeverityInfo, event, attrs...)
|
||||
}
|
||||
Reference in New Issue
Block a user